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 "X86Subtarget.h"
18 #include "llvm/CallingConv.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Function.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/CodeGen/SSARegMap.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/ADT/Statistic.h"
40 #include "llvm/Support/CommandLine.h"
41 static cl::opt<bool> EnableFastCC("enable-x86-fastcc", cl::Hidden,
42 cl::desc("Enable fastcc on X86"));
45 // X86 Specific DAG Nodes
48 // Start the numbering where the builtin ops leave off.
49 FIRST_NUMBER = ISD::BUILTIN_OP_END,
51 /// FILD64m - This instruction implements SINT_TO_FP with a
52 /// 64-bit source in memory and a FP reg result. This corresponds to
53 /// the X86::FILD64m instruction. It has two inputs (token chain and
54 /// address) and two outputs (FP value and token chain).
57 /// FP_TO_INT*_IN_MEM - This instruction implements FP_TO_SINT with the
58 /// integer destination in memory and a FP reg source. This corresponds
59 /// to the X86::FIST*m instructions and the rounding mode change stuff. It
60 /// has two inputs (token chain and address) and two outputs (FP value and
66 /// CALL/TAILCALL - These operations represent an abstract X86 call
67 /// instruction, which includes a bunch of information. In particular the
68 /// operands of these node are:
70 /// #0 - The incoming token chain
72 /// #2 - The number of arg bytes the caller pushes on the stack.
73 /// #3 - The number of arg bytes the callee pops off the stack.
74 /// #4 - The value to pass in AL/AX/EAX (optional)
75 /// #5 - The value to pass in DL/DX/EDX (optional)
77 /// The result values of these nodes are:
79 /// #0 - The outgoing token chain
80 /// #1 - The first register result value (optional)
81 /// #2 - The second register result value (optional)
83 /// The CALL vs TAILCALL distinction boils down to whether the callee is
84 /// known not to modify the caller's stack frame, as is standard with
92 //===----------------------------------------------------------------------===//
93 // X86TargetLowering - X86 Implementation of the TargetLowering interface
95 class X86TargetLowering : public TargetLowering {
96 int VarArgsFrameIndex; // FrameIndex for start of varargs area.
97 int ReturnAddrIndex; // FrameIndex for return slot.
98 int BytesToPopOnReturn; // Number of arg bytes ret should pop.
99 int BytesCallerReserves; // Number of arg bytes caller makes.
101 X86TargetLowering(TargetMachine &TM) : TargetLowering(TM) {
102 // Set up the TargetLowering object.
104 // X86 is weird, it always uses i8 for shift amounts and setcc results.
105 setShiftAmountType(MVT::i8);
106 setSetCCResultType(MVT::i8);
107 setSetCCResultContents(ZeroOrOneSetCCResult);
108 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
110 // Set up the register classes.
111 // FIXME: Eliminate these two classes when legalize can handle promotions
113 addRegisterClass(MVT::i1, X86::R8RegisterClass);
114 addRegisterClass(MVT::i8, X86::R8RegisterClass);
115 addRegisterClass(MVT::i16, X86::R16RegisterClass);
116 addRegisterClass(MVT::i32, X86::R32RegisterClass);
118 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
120 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
121 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
122 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
123 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
125 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
127 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
128 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
131 // We can handle SINT_TO_FP and FP_TO_SINT from/TO i64 even though i64
133 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
134 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
135 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
136 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
139 // Handle FP_TO_UINT by promoting the destination to a larger signed
141 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
142 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
143 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
146 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
148 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
150 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
151 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
152 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
154 setOperationAction(ISD::BRCONDTWOWAY , MVT::Other, Expand);
155 setOperationAction(ISD::BRTWOWAY_CC , MVT::Other, Expand);
156 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
157 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Expand);
158 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
159 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
160 setOperationAction(ISD::SEXTLOAD , MVT::i1 , Expand);
161 setOperationAction(ISD::SREM , MVT::f64 , Expand);
162 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
163 setOperationAction(ISD::CTTZ , MVT::i8 , Expand);
164 setOperationAction(ISD::CTLZ , MVT::i8 , Expand);
165 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
166 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
167 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
168 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
169 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
170 setOperationAction(ISD::CTLZ , MVT::i32 , Expand);
172 setOperationAction(ISD::READIO , MVT::i1 , Expand);
173 setOperationAction(ISD::READIO , MVT::i8 , Expand);
174 setOperationAction(ISD::READIO , MVT::i16 , Expand);
175 setOperationAction(ISD::READIO , MVT::i32 , Expand);
176 setOperationAction(ISD::WRITEIO , MVT::i1 , Expand);
177 setOperationAction(ISD::WRITEIO , MVT::i8 , Expand);
178 setOperationAction(ISD::WRITEIO , MVT::i16 , Expand);
179 setOperationAction(ISD::WRITEIO , MVT::i32 , Expand);
181 // These should be promoted to a larger select which is supported.
182 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
183 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
186 // Set up the FP register classes.
187 addRegisterClass(MVT::f32, X86::RXMMRegisterClass);
188 addRegisterClass(MVT::f64, X86::RXMMRegisterClass);
190 // SSE has no load+extend ops
191 setOperationAction(ISD::EXTLOAD, MVT::f32, Expand);
192 setOperationAction(ISD::ZEXTLOAD, MVT::f32, Expand);
194 // SSE has no i16 to fp conversion, only i32
195 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
196 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
198 // Expand FP_TO_UINT into a select.
199 // FIXME: We would like to use a Custom expander here eventually to do
200 // the optimal thing for SSE vs. the default expansion in the legalizer.
201 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
203 // We don't support sin/cos/sqrt/fmod
204 setOperationAction(ISD::FSIN , MVT::f64, Expand);
205 setOperationAction(ISD::FCOS , MVT::f64, Expand);
206 setOperationAction(ISD::FABS , MVT::f64, Expand);
207 setOperationAction(ISD::FNEG , MVT::f64, Expand);
208 setOperationAction(ISD::SREM , MVT::f64, Expand);
209 setOperationAction(ISD::FSIN , MVT::f32, Expand);
210 setOperationAction(ISD::FCOS , MVT::f32, Expand);
211 setOperationAction(ISD::FABS , MVT::f32, Expand);
212 setOperationAction(ISD::FNEG , MVT::f32, Expand);
213 setOperationAction(ISD::SREM , MVT::f32, Expand);
215 addLegalFPImmediate(+0.0); // xorps / xorpd
217 // Set up the FP register classes.
218 addRegisterClass(MVT::f64, X86::RFPRegisterClass);
221 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
222 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
225 addLegalFPImmediate(+0.0); // FLD0
226 addLegalFPImmediate(+1.0); // FLD1
227 addLegalFPImmediate(-0.0); // FLD0/FCHS
228 addLegalFPImmediate(-1.0); // FLD1/FCHS
230 computeRegisterProperties();
232 maxStoresPerMemSet = 8; // For %llvm.memset -> sequence of stores
233 maxStoresPerMemCpy = 8; // For %llvm.memcpy -> sequence of stores
234 maxStoresPerMemMove = 8; // For %llvm.memmove -> sequence of stores
235 allowUnalignedStores = true; // x86 supports it!
238 // Return the number of bytes that a function should pop when it returns (in
239 // addition to the space used by the return address).
241 unsigned getBytesToPopOnReturn() const { return BytesToPopOnReturn; }
243 // Return the number of bytes that the caller reserves for arguments passed
245 unsigned getBytesCallerReserves() const { return BytesCallerReserves; }
247 /// LowerOperation - Provide custom lowering hooks for some operations.
249 virtual SDOperand LowerOperation(SDOperand Op, SelectionDAG &DAG);
251 /// LowerArguments - This hook must be implemented to indicate how we should
252 /// lower the arguments for the specified function, into the specified DAG.
253 virtual std::vector<SDOperand>
254 LowerArguments(Function &F, SelectionDAG &DAG);
256 /// LowerCallTo - This hook lowers an abstract call to a function into an
258 virtual std::pair<SDOperand, SDOperand>
259 LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg, unsigned CC,
260 bool isTailCall, SDOperand Callee, ArgListTy &Args,
263 virtual SDOperand LowerVAStart(SDOperand Chain, SDOperand VAListP,
264 Value *VAListV, SelectionDAG &DAG);
265 virtual std::pair<SDOperand,SDOperand>
266 LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
267 const Type *ArgTy, SelectionDAG &DAG);
269 virtual std::pair<SDOperand, SDOperand>
270 LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
273 SDOperand getReturnAddressFrameIndex(SelectionDAG &DAG);
276 // C Calling Convention implementation.
277 std::vector<SDOperand> LowerCCCArguments(Function &F, SelectionDAG &DAG);
278 std::pair<SDOperand, SDOperand>
279 LowerCCCCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
281 SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG);
283 // Fast Calling Convention implementation.
284 std::vector<SDOperand> LowerFastCCArguments(Function &F, SelectionDAG &DAG);
285 std::pair<SDOperand, SDOperand>
286 LowerFastCCCallTo(SDOperand Chain, const Type *RetTy, bool isTailCall,
287 SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG);
291 std::vector<SDOperand>
292 X86TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
293 if (F.getCallingConv() == CallingConv::Fast && EnableFastCC)
294 return LowerFastCCArguments(F, DAG);
295 return LowerCCCArguments(F, DAG);
298 std::pair<SDOperand, SDOperand>
299 X86TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
300 bool isVarArg, unsigned CallingConv,
302 SDOperand Callee, ArgListTy &Args,
304 assert((!isVarArg || CallingConv == CallingConv::C) &&
305 "Only C takes varargs!");
306 if (CallingConv == CallingConv::Fast && EnableFastCC)
307 return LowerFastCCCallTo(Chain, RetTy, isTailCall, Callee, Args, DAG);
308 return LowerCCCCallTo(Chain, RetTy, isVarArg, isTailCall, Callee, Args, DAG);
311 //===----------------------------------------------------------------------===//
312 // C Calling Convention implementation
313 //===----------------------------------------------------------------------===//
315 std::vector<SDOperand>
316 X86TargetLowering::LowerCCCArguments(Function &F, SelectionDAG &DAG) {
317 std::vector<SDOperand> ArgValues;
319 MachineFunction &MF = DAG.getMachineFunction();
320 MachineFrameInfo *MFI = MF.getFrameInfo();
322 // Add DAG nodes to load the arguments... On entry to a function on the X86,
323 // the stack frame looks like this:
325 // [ESP] -- return address
326 // [ESP + 4] -- first argument (leftmost lexically)
327 // [ESP + 8] -- second argument, if first argument is four bytes in size
330 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
331 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
332 MVT::ValueType ObjectVT = getValueType(I->getType());
333 unsigned ArgIncrement = 4;
336 default: assert(0 && "Unhandled argument type!");
338 case MVT::i8: ObjSize = 1; break;
339 case MVT::i16: ObjSize = 2; break;
340 case MVT::i32: ObjSize = 4; break;
341 case MVT::i64: ObjSize = ArgIncrement = 8; break;
342 case MVT::f32: ObjSize = 4; break;
343 case MVT::f64: ObjSize = ArgIncrement = 8; break;
345 // Create the frame index object for this incoming parameter...
346 int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
348 // Create the SelectionDAG nodes corresponding to a load from this parameter
349 SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
351 // Don't codegen dead arguments. FIXME: remove this check when we can nuke
355 ArgValue = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
356 DAG.getSrcValue(NULL));
358 if (MVT::isInteger(ObjectVT))
359 ArgValue = DAG.getConstant(0, ObjectVT);
361 ArgValue = DAG.getConstantFP(0, ObjectVT);
363 ArgValues.push_back(ArgValue);
365 ArgOffset += ArgIncrement; // Move on to the next argument...
368 // If the function takes variable number of arguments, make a frame index for
369 // the start of the first vararg value... for expansion of llvm.va_start.
371 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
372 ReturnAddrIndex = 0; // No return address slot generated yet.
373 BytesToPopOnReturn = 0; // Callee pops nothing.
374 BytesCallerReserves = ArgOffset;
376 // Finally, inform the code generator which regs we return values in.
377 switch (getValueType(F.getReturnType())) {
378 default: assert(0 && "Unknown type!");
379 case MVT::isVoid: break;
384 MF.addLiveOut(X86::EAX);
387 MF.addLiveOut(X86::EAX);
388 MF.addLiveOut(X86::EDX);
392 MF.addLiveOut(X86::ST0);
398 std::pair<SDOperand, SDOperand>
399 X86TargetLowering::LowerCCCCallTo(SDOperand Chain, const Type *RetTy,
400 bool isVarArg, bool isTailCall,
401 SDOperand Callee, ArgListTy &Args,
403 // Count how many bytes are to be pushed on the stack.
404 unsigned NumBytes = 0;
408 Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
409 DAG.getConstant(0, getPointerTy()));
411 for (unsigned i = 0, e = Args.size(); i != e; ++i)
412 switch (getValueType(Args[i].second)) {
413 default: assert(0 && "Unknown value type!");
427 Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
428 DAG.getConstant(NumBytes, getPointerTy()));
430 // Arguments go on the stack in reverse order, as specified by the ABI.
431 unsigned ArgOffset = 0;
432 SDOperand StackPtr = DAG.getCopyFromReg(DAG.getEntryNode(),
434 std::vector<SDOperand> Stores;
436 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
437 SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
438 PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
440 switch (getValueType(Args[i].second)) {
441 default: assert(0 && "Unexpected ValueType for argument!");
445 // Promote the integer to 32 bits. If the input type is signed use a
446 // sign extend, otherwise use a zero extend.
447 if (Args[i].second->isSigned())
448 Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
450 Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
455 Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
456 Args[i].first, PtrOff,
457 DAG.getSrcValue(NULL)));
462 Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
463 Args[i].first, PtrOff,
464 DAG.getSrcValue(NULL)));
469 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
472 std::vector<MVT::ValueType> RetVals;
473 MVT::ValueType RetTyVT = getValueType(RetTy);
474 RetVals.push_back(MVT::Other);
476 // The result values produced have to be legal. Promote the result.
478 case MVT::isVoid: break;
480 RetVals.push_back(RetTyVT);
485 RetVals.push_back(MVT::i32);
489 RetVals.push_back(MVT::f32);
491 RetVals.push_back(MVT::f64);
494 RetVals.push_back(MVT::i32);
495 RetVals.push_back(MVT::i32);
498 std::vector<SDOperand> Ops;
499 Ops.push_back(Chain);
500 Ops.push_back(Callee);
501 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
502 Ops.push_back(DAG.getConstant(0, getPointerTy()));
503 SDOperand TheCall = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
505 Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, TheCall);
509 case MVT::isVoid: break;
511 ResultVal = TheCall.getValue(1);
516 ResultVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, TheCall.getValue(1));
519 // FIXME: we would really like to remember that this FP_ROUND operation is
520 // okay to eliminate if we allow excess FP precision.
521 ResultVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, TheCall.getValue(1));
524 ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, TheCall.getValue(1),
525 TheCall.getValue(2));
529 return std::make_pair(ResultVal, Chain);
533 X86TargetLowering::LowerVAStart(SDOperand Chain, SDOperand VAListP,
534 Value *VAListV, SelectionDAG &DAG) {
535 // vastart just stores the address of the VarArgsFrameIndex slot.
536 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
537 return DAG.getNode(ISD::STORE, MVT::Other, Chain, FR, VAListP,
538 DAG.getSrcValue(VAListV));
542 std::pair<SDOperand,SDOperand>
543 X86TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP,
544 Value *VAListV, const Type *ArgTy,
546 MVT::ValueType ArgVT = getValueType(ArgTy);
547 SDOperand Val = DAG.getLoad(MVT::i32, Chain,
548 VAListP, DAG.getSrcValue(VAListV));
549 SDOperand Result = DAG.getLoad(ArgVT, Chain, Val,
550 DAG.getSrcValue(NULL));
552 if (ArgVT == MVT::i32)
555 assert((ArgVT == MVT::i64 || ArgVT == MVT::f64) &&
556 "Other types should have been promoted for varargs!");
559 Val = DAG.getNode(ISD::ADD, Val.getValueType(), Val,
560 DAG.getConstant(Amt, Val.getValueType()));
561 Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain,
562 Val, VAListP, DAG.getSrcValue(VAListV));
563 return std::make_pair(Result, Chain);
566 //===----------------------------------------------------------------------===//
567 // Fast Calling Convention implementation
568 //===----------------------------------------------------------------------===//
570 // The X86 'fast' calling convention passes up to two integer arguments in
571 // registers (an appropriate portion of EAX/EDX), passes arguments in C order,
572 // and requires that the callee pop its arguments off the stack (allowing proper
573 // tail calls), and has the same return value conventions as C calling convs.
575 // This calling convention always arranges for the callee pop value to be 8n+4
576 // bytes, which is needed for tail recursion elimination and stack alignment
579 // Note that this can be enhanced in the future to pass fp vals in registers
580 // (when we have a global fp allocator) and do other tricks.
583 /// AddLiveIn - This helper function adds the specified physical register to the
584 /// MachineFunction as a live in value. It also creates a corresponding virtual
586 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
587 TargetRegisterClass *RC) {
588 assert(RC->contains(PReg) && "Not the correct regclass!");
589 unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
590 MF.addLiveIn(PReg, VReg);
595 std::vector<SDOperand>
596 X86TargetLowering::LowerFastCCArguments(Function &F, SelectionDAG &DAG) {
597 std::vector<SDOperand> ArgValues;
599 MachineFunction &MF = DAG.getMachineFunction();
600 MachineFrameInfo *MFI = MF.getFrameInfo();
602 // Add DAG nodes to load the arguments... On entry to a function the stack
603 // frame looks like this:
605 // [ESP] -- return address
606 // [ESP + 4] -- first nonreg argument (leftmost lexically)
607 // [ESP + 8] -- second nonreg argument, if first argument is 4 bytes in size
609 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
611 // Keep track of the number of integer regs passed so far. This can be either
612 // 0 (neither EAX or EDX used), 1 (EAX is used) or 2 (EAX and EDX are both
614 unsigned NumIntRegs = 0;
616 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
617 MVT::ValueType ObjectVT = getValueType(I->getType());
618 unsigned ArgIncrement = 4;
619 unsigned ObjSize = 0;
623 default: assert(0 && "Unhandled argument type!");
626 if (NumIntRegs < 2) {
627 if (!I->use_empty()) {
628 unsigned VReg = AddLiveIn(MF, NumIntRegs ? X86::DL : X86::AL,
629 X86::R8RegisterClass);
630 ArgValue = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i8);
631 DAG.setRoot(ArgValue.getValue(1));
640 if (NumIntRegs < 2) {
641 if (!I->use_empty()) {
642 unsigned VReg = AddLiveIn(MF, NumIntRegs ? X86::DX : X86::AX,
643 X86::R16RegisterClass);
644 ArgValue = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i16);
645 DAG.setRoot(ArgValue.getValue(1));
653 if (NumIntRegs < 2) {
654 if (!I->use_empty()) {
655 unsigned VReg = AddLiveIn(MF,NumIntRegs ? X86::EDX : X86::EAX,
656 X86::R32RegisterClass);
657 ArgValue = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
658 DAG.setRoot(ArgValue.getValue(1));
666 if (NumIntRegs == 0) {
667 if (!I->use_empty()) {
668 unsigned BotReg = AddLiveIn(MF, X86::EAX, X86::R32RegisterClass);
669 unsigned TopReg = AddLiveIn(MF, X86::EDX, X86::R32RegisterClass);
671 SDOperand Low = DAG.getCopyFromReg(DAG.getRoot(), BotReg, MVT::i32);
672 SDOperand Hi = DAG.getCopyFromReg(Low.getValue(1), TopReg, MVT::i32);
673 DAG.setRoot(Hi.getValue(1));
675 ArgValue = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Low, Hi);
679 } else if (NumIntRegs == 1) {
680 if (!I->use_empty()) {
681 unsigned BotReg = AddLiveIn(MF, X86::EDX, X86::R32RegisterClass);
682 SDOperand Low = DAG.getCopyFromReg(DAG.getRoot(), BotReg, MVT::i32);
683 DAG.setRoot(Low.getValue(1));
685 // Load the high part from memory.
686 // Create the frame index object for this incoming parameter...
687 int FI = MFI->CreateFixedObject(4, ArgOffset);
688 SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
689 SDOperand Hi = DAG.getLoad(MVT::i32, DAG.getEntryNode(), FIN,
690 DAG.getSrcValue(NULL));
691 ArgValue = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Low, Hi);
697 ObjSize = ArgIncrement = 8;
699 case MVT::f32: ObjSize = 4; break;
700 case MVT::f64: ObjSize = ArgIncrement = 8; break;
703 // Don't codegen dead arguments. FIXME: remove this check when we can nuke
705 if (ObjSize && !I->use_empty()) {
706 // Create the frame index object for this incoming parameter...
707 int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
709 // Create the SelectionDAG nodes corresponding to a load from this
711 SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
713 ArgValue = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
714 DAG.getSrcValue(NULL));
715 } else if (ArgValue.Val == 0) {
716 if (MVT::isInteger(ObjectVT))
717 ArgValue = DAG.getConstant(0, ObjectVT);
719 ArgValue = DAG.getConstantFP(0, ObjectVT);
721 ArgValues.push_back(ArgValue);
724 ArgOffset += ArgIncrement; // Move on to the next argument.
727 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
728 // arguments and the arguments after the retaddr has been pushed are aligned.
729 if ((ArgOffset & 7) == 0)
732 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
733 ReturnAddrIndex = 0; // No return address slot generated yet.
734 BytesToPopOnReturn = ArgOffset; // Callee pops all stack arguments.
735 BytesCallerReserves = 0;
737 // Finally, inform the code generator which regs we return values in.
738 switch (getValueType(F.getReturnType())) {
739 default: assert(0 && "Unknown type!");
740 case MVT::isVoid: break;
745 MF.addLiveOut(X86::EAX);
748 MF.addLiveOut(X86::EAX);
749 MF.addLiveOut(X86::EDX);
753 MF.addLiveOut(X86::ST0);
759 std::pair<SDOperand, SDOperand>
760 X86TargetLowering::LowerFastCCCallTo(SDOperand Chain, const Type *RetTy,
761 bool isTailCall, SDOperand Callee,
762 ArgListTy &Args, SelectionDAG &DAG) {
763 // Count how many bytes are to be pushed on the stack.
764 unsigned NumBytes = 0;
766 // Keep track of the number of integer regs passed so far. This can be either
767 // 0 (neither EAX or EDX used), 1 (EAX is used) or 2 (EAX and EDX are both
769 unsigned NumIntRegs = 0;
771 for (unsigned i = 0, e = Args.size(); i != e; ++i)
772 switch (getValueType(Args[i].second)) {
773 default: assert(0 && "Unknown value type!");
778 if (NumIntRegs < 2) {
787 if (NumIntRegs == 0) {
790 } else if (NumIntRegs == 1) {
802 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
803 // arguments and the arguments after the retaddr has been pushed are aligned.
804 if ((NumBytes & 7) == 0)
807 Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
808 DAG.getConstant(NumBytes, getPointerTy()));
810 // Arguments go on the stack in reverse order, as specified by the ABI.
811 unsigned ArgOffset = 0;
812 SDOperand StackPtr = DAG.getCopyFromReg(DAG.getEntryNode(),
815 std::vector<SDOperand> Stores;
816 std::vector<SDOperand> RegValuesToPass;
817 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
818 switch (getValueType(Args[i].second)) {
819 default: assert(0 && "Unexpected ValueType for argument!");
824 if (NumIntRegs < 2) {
825 RegValuesToPass.push_back(Args[i].first);
831 SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
832 PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
833 Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
834 Args[i].first, PtrOff,
835 DAG.getSrcValue(NULL)));
840 if (NumIntRegs < 2) { // Can pass part of it in regs?
841 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
842 Args[i].first, DAG.getConstant(1, MVT::i32));
843 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
844 Args[i].first, DAG.getConstant(0, MVT::i32));
845 RegValuesToPass.push_back(Lo);
847 if (NumIntRegs < 2) { // Pass both parts in regs?
848 RegValuesToPass.push_back(Hi);
851 // Pass the high part in memory.
852 SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
853 PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
854 Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
855 Hi, PtrOff, DAG.getSrcValue(NULL)));
862 SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
863 PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
864 Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
865 Args[i].first, PtrOff,
866 DAG.getSrcValue(NULL)));
872 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
874 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
875 // arguments and the arguments after the retaddr has been pushed are aligned.
876 if ((ArgOffset & 7) == 0)
879 std::vector<MVT::ValueType> RetVals;
880 MVT::ValueType RetTyVT = getValueType(RetTy);
882 RetVals.push_back(MVT::Other);
884 // The result values produced have to be legal. Promote the result.
886 case MVT::isVoid: break;
888 RetVals.push_back(RetTyVT);
893 RetVals.push_back(MVT::i32);
897 RetVals.push_back(MVT::f32);
899 RetVals.push_back(MVT::f64);
902 RetVals.push_back(MVT::i32);
903 RetVals.push_back(MVT::i32);
907 std::vector<SDOperand> Ops;
908 Ops.push_back(Chain);
909 Ops.push_back(Callee);
910 Ops.push_back(DAG.getConstant(ArgOffset, getPointerTy()));
911 // Callee pops all arg values on the stack.
912 Ops.push_back(DAG.getConstant(ArgOffset, getPointerTy()));
914 // Pass register arguments as needed.
915 Ops.insert(Ops.end(), RegValuesToPass.begin(), RegValuesToPass.end());
917 SDOperand TheCall = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
919 Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, TheCall);
923 case MVT::isVoid: break;
925 ResultVal = TheCall.getValue(1);
930 ResultVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, TheCall.getValue(1));
933 // FIXME: we would really like to remember that this FP_ROUND operation is
934 // okay to eliminate if we allow excess FP precision.
935 ResultVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, TheCall.getValue(1));
938 ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, TheCall.getValue(1),
939 TheCall.getValue(2));
943 return std::make_pair(ResultVal, Chain);
946 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
947 if (ReturnAddrIndex == 0) {
948 // Set up a frame object for the return address.
949 MachineFunction &MF = DAG.getMachineFunction();
950 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
953 return DAG.getFrameIndex(ReturnAddrIndex, MVT::i32);
958 std::pair<SDOperand, SDOperand> X86TargetLowering::
959 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
962 if (Depth) // Depths > 0 not supported yet!
963 Result = DAG.getConstant(0, getPointerTy());
965 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
967 // Just load the return address
968 Result = DAG.getLoad(MVT::i32, DAG.getEntryNode(), RetAddrFI,
969 DAG.getSrcValue(NULL));
971 Result = DAG.getNode(ISD::SUB, MVT::i32, RetAddrFI,
972 DAG.getConstant(4, MVT::i32));
974 return std::make_pair(Result, Chain);
977 //===----------------------------------------------------------------------===//
978 // X86 Custom Lowering Hooks
979 //===----------------------------------------------------------------------===//
981 /// LowerOperation - Provide custom lowering hooks for some operations.
983 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
984 switch (Op.getOpcode()) {
985 default: assert(0 && "Should not custom lower this!");
986 case ISD::SINT_TO_FP: {
987 assert(Op.getValueType() == MVT::f64 &&
988 Op.getOperand(0).getValueType() == MVT::i64 &&
989 "Unknown SINT_TO_FP to lower!");
990 // We lower sint64->FP into a store to a temporary stack slot, followed by a
992 MachineFunction &MF = DAG.getMachineFunction();
993 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
994 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
995 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
996 Op.getOperand(0), StackSlot, DAG.getSrcValue(NULL));
997 std::vector<MVT::ValueType> RTs;
998 RTs.push_back(MVT::f64);
999 RTs.push_back(MVT::Other);
1000 std::vector<SDOperand> Ops;
1001 Ops.push_back(Store);
1002 Ops.push_back(StackSlot);
1003 return DAG.getNode(X86ISD::FILD64m, RTs, Ops);
1005 case ISD::FP_TO_SINT: {
1006 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
1007 Op.getOperand(0).getValueType() == MVT::f64 &&
1008 "Unknown FP_TO_SINT to lower!");
1009 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
1011 MachineFunction &MF = DAG.getMachineFunction();
1012 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
1013 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
1014 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1017 switch (Op.getValueType()) {
1018 default: assert(0 && "Invalid FP_TO_SINT to lower!");
1019 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
1020 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
1021 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
1024 // Build the FP_TO_INT*_IN_MEM
1025 std::vector<SDOperand> Ops;
1026 Ops.push_back(DAG.getEntryNode());
1027 Ops.push_back(Op.getOperand(0));
1028 Ops.push_back(StackSlot);
1029 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops);
1032 return DAG.getLoad(Op.getValueType(), FIST, StackSlot,
1033 DAG.getSrcValue(NULL));
1039 //===----------------------------------------------------------------------===//
1040 // Pattern Matcher Implementation
1041 //===----------------------------------------------------------------------===//
1044 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
1045 /// SDOperand's instead of register numbers for the leaves of the matched
1047 struct X86ISelAddressMode {
1053 struct { // This is really a union, discriminated by BaseType!
1063 X86ISelAddressMode()
1064 : BaseType(RegBase), Scale(1), IndexReg(), Disp(), GV(0) {
1072 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
1074 //===--------------------------------------------------------------------===//
1075 /// ISel - X86 specific code to select X86 machine instructions for
1076 /// SelectionDAG operations.
1078 class ISel : public SelectionDAGISel {
1079 /// ContainsFPCode - Every instruction we select that uses or defines a FP
1080 /// register should set this to true.
1081 bool ContainsFPCode;
1083 /// X86Lowering - This object fully describes how to lower LLVM code to an
1084 /// X86-specific SelectionDAG.
1085 X86TargetLowering X86Lowering;
1087 /// RegPressureMap - This keeps an approximate count of the number of
1088 /// registers required to evaluate each node in the graph.
1089 std::map<SDNode*, unsigned> RegPressureMap;
1091 /// ExprMap - As shared expressions are codegen'd, we keep track of which
1092 /// vreg the value is produced in, so we only emit one copy of each compiled
1094 std::map<SDOperand, unsigned> ExprMap;
1096 /// TheDAG - The DAG being selected during Select* operations.
1097 SelectionDAG *TheDAG;
1099 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
1100 /// make the right decision when generating code for different targets.
1101 const X86Subtarget *Subtarget;
1103 ISel(TargetMachine &TM) : SelectionDAGISel(X86Lowering), X86Lowering(TM) {
1104 Subtarget = &TM.getSubtarget<X86Subtarget>();
1107 virtual const char *getPassName() const {
1108 return "X86 Pattern Instruction Selection";
1111 unsigned getRegPressure(SDOperand O) {
1112 return RegPressureMap[O.Val];
1114 unsigned ComputeRegPressure(SDOperand O);
1116 /// InstructionSelectBasicBlock - This callback is invoked by
1117 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
1118 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
1120 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
1122 bool isFoldableLoad(SDOperand Op, SDOperand OtherOp,
1123 bool FloatPromoteOk = false);
1124 void EmitFoldedLoad(SDOperand Op, X86AddressMode &AM);
1125 bool TryToFoldLoadOpStore(SDNode *Node);
1126 bool EmitOrOpOp(SDOperand Op1, SDOperand Op2, unsigned DestReg);
1127 void EmitCMP(SDOperand LHS, SDOperand RHS, bool isOnlyUse);
1128 bool EmitBranchCC(MachineBasicBlock *Dest, SDOperand Chain, SDOperand Cond);
1129 void EmitSelectCC(SDOperand Cond, SDOperand True, SDOperand False,
1130 MVT::ValueType SVT, unsigned RDest);
1131 unsigned SelectExpr(SDOperand N);
1133 X86AddressMode SelectAddrExprs(const X86ISelAddressMode &IAM);
1134 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM);
1135 void SelectAddress(SDOperand N, X86AddressMode &AM);
1136 bool EmitPotentialTailCall(SDNode *Node);
1137 void EmitFastCCToFastCCTailCall(SDNode *TailCallNode);
1138 void Select(SDOperand N);
1142 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
1143 /// the main function.
1144 static void EmitSpecialCodeForMain(MachineBasicBlock *BB,
1145 MachineFrameInfo *MFI) {
1146 // Switch the FPU to 64-bit precision mode for better compatibility and speed.
1147 int CWFrameIdx = MFI->CreateStackObject(2, 2);
1148 addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
1150 // Set the high part to be 64-bit precision.
1151 addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
1152 CWFrameIdx, 1).addImm(2);
1154 // Reload the modified control word now.
1155 addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
1158 void ISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
1159 // If this function has live-in values, emit the copies from pregs to vregs at
1160 // the top of the function, before anything else.
1161 MachineBasicBlock *BB = MF.begin();
1162 if (MF.livein_begin() != MF.livein_end()) {
1163 SSARegMap *RegMap = MF.getSSARegMap();
1164 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1165 E = MF.livein_end(); LI != E; ++LI) {
1166 const TargetRegisterClass *RC = RegMap->getRegClass(LI->second);
1167 if (RC == X86::R8RegisterClass) {
1168 BuildMI(BB, X86::MOV8rr, 1, LI->second).addReg(LI->first);
1169 } else if (RC == X86::R16RegisterClass) {
1170 BuildMI(BB, X86::MOV16rr, 1, LI->second).addReg(LI->first);
1171 } else if (RC == X86::R32RegisterClass) {
1172 BuildMI(BB, X86::MOV32rr, 1, LI->second).addReg(LI->first);
1173 } else if (RC == X86::RFPRegisterClass) {
1174 BuildMI(BB, X86::FpMOV, 1, LI->second).addReg(LI->first);
1175 } else if (RC == X86::RXMMRegisterClass) {
1176 BuildMI(BB, X86::MOVAPDrr, 1, LI->second).addReg(LI->first);
1178 assert(0 && "Unknown regclass!");
1184 // If this is main, emit special code for main.
1185 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
1186 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
1190 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
1191 /// when it has created a SelectionDAG for us to codegen.
1192 void ISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
1193 // While we're doing this, keep track of whether we see any FP code for
1194 // FP_REG_KILL insertion.
1195 ContainsFPCode = false;
1196 MachineFunction *MF = BB->getParent();
1198 // Scan the PHI nodes that already are inserted into this basic block. If any
1199 // of them is a PHI of a floating point value, we need to insert an
1201 SSARegMap *RegMap = MF->getSSARegMap();
1202 if (BB != MF->begin())
1203 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
1205 assert(I->getOpcode() == X86::PHI &&
1206 "Isn't just PHI nodes?");
1207 if (RegMap->getRegClass(I->getOperand(0).getReg()) ==
1208 X86::RFPRegisterClass) {
1209 ContainsFPCode = true;
1214 // Compute the RegPressureMap, which is an approximation for the number of
1215 // registers required to compute each node.
1216 ComputeRegPressure(DAG.getRoot());
1220 // Codegen the basic block.
1221 Select(DAG.getRoot());
1225 // Finally, look at all of the successors of this block. If any contain a PHI
1226 // node of FP type, we need to insert an FP_REG_KILL in this block.
1227 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
1228 E = BB->succ_end(); SI != E && !ContainsFPCode; ++SI)
1229 for (MachineBasicBlock::iterator I = (*SI)->begin(), E = (*SI)->end();
1230 I != E && I->getOpcode() == X86::PHI; ++I) {
1231 if (RegMap->getRegClass(I->getOperand(0).getReg()) ==
1232 X86::RFPRegisterClass) {
1233 ContainsFPCode = true;
1238 // Final check, check LLVM BB's that are successors to the LLVM BB
1239 // corresponding to BB for FP PHI nodes.
1240 const BasicBlock *LLVMBB = BB->getBasicBlock();
1242 if (!ContainsFPCode)
1243 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
1244 SI != E && !ContainsFPCode; ++SI)
1245 for (BasicBlock::const_iterator II = SI->begin();
1246 (PN = dyn_cast<PHINode>(II)); ++II)
1247 if (PN->getType()->isFloatingPoint()) {
1248 ContainsFPCode = true;
1253 // Insert FP_REG_KILL instructions into basic blocks that need them. This
1254 // only occurs due to the floating point stackifier not being aggressive
1255 // enough to handle arbitrary global stackification.
1257 // Currently we insert an FP_REG_KILL instruction into each block that uses or
1258 // defines a floating point virtual register.
1260 // When the global register allocators (like linear scan) finally update live
1261 // variable analysis, we can keep floating point values in registers across
1262 // basic blocks. This will be a huge win, but we are waiting on the global
1263 // allocators before we can do this.
1265 if (ContainsFPCode) {
1266 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
1270 // Clear state used for selection.
1272 RegPressureMap.clear();
1276 // ComputeRegPressure - Compute the RegPressureMap, which is an approximation
1277 // for the number of registers required to compute each node. This is basically
1278 // computing a generalized form of the Sethi-Ullman number for each node.
1279 unsigned ISel::ComputeRegPressure(SDOperand O) {
1281 unsigned &Result = RegPressureMap[N];
1282 if (Result) return Result;
1284 // FIXME: Should operations like CALL (which clobber lots o regs) have a
1285 // higher fixed cost??
1287 if (N->getNumOperands() == 0) {
1290 unsigned MaxRegUse = 0;
1291 unsigned NumExtraMaxRegUsers = 0;
1292 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1294 if (N->getOperand(i).getOpcode() == ISD::Constant)
1297 Regs = ComputeRegPressure(N->getOperand(i));
1298 if (Regs > MaxRegUse) {
1300 NumExtraMaxRegUsers = 0;
1301 } else if (Regs == MaxRegUse &&
1302 N->getOperand(i).getValueType() != MVT::Other) {
1303 ++NumExtraMaxRegUsers;
1307 if (O.getOpcode() != ISD::TokenFactor)
1308 Result = MaxRegUse+NumExtraMaxRegUsers;
1310 Result = MaxRegUse == 1 ? 0 : MaxRegUse-1;
1313 //std::cerr << " WEIGHT: " << Result << " "; N->dump(); std::cerr << "\n";
1317 /// NodeTransitivelyUsesValue - Return true if N or any of its uses uses Op.
1318 /// The DAG cannot have cycles in it, by definition, so the visited set is not
1319 /// needed to prevent infinite loops. The DAG CAN, however, have unbounded
1320 /// reuse, so it prevents exponential cases.
1322 static bool NodeTransitivelyUsesValue(SDOperand N, SDOperand Op,
1323 std::set<SDNode*> &Visited) {
1324 if (N == Op) return true; // Found it.
1325 SDNode *Node = N.Val;
1326 if (Node->getNumOperands() == 0 || // Leaf?
1327 Node->getNodeDepth() <= Op.getNodeDepth()) return false; // Can't find it?
1328 if (!Visited.insert(Node).second) return false; // Already visited?
1330 // Recurse for the first N-1 operands.
1331 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1332 if (NodeTransitivelyUsesValue(Node->getOperand(i), Op, Visited))
1335 // Tail recurse for the last operand.
1336 return NodeTransitivelyUsesValue(Node->getOperand(0), Op, Visited);
1339 X86AddressMode ISel::SelectAddrExprs(const X86ISelAddressMode &IAM) {
1340 X86AddressMode Result;
1342 // If we need to emit two register operands, emit the one with the highest
1343 // register pressure first.
1344 if (IAM.BaseType == X86ISelAddressMode::RegBase &&
1345 IAM.Base.Reg.Val && IAM.IndexReg.Val) {
1346 bool EmitBaseThenIndex;
1347 if (getRegPressure(IAM.Base.Reg) > getRegPressure(IAM.IndexReg)) {
1348 std::set<SDNode*> Visited;
1349 EmitBaseThenIndex = true;
1350 // If Base ends up pointing to Index, we must emit index first. This is
1351 // because of the way we fold loads, we may end up doing bad things with
1353 if (NodeTransitivelyUsesValue(IAM.Base.Reg, IAM.IndexReg, Visited))
1354 EmitBaseThenIndex = false;
1356 std::set<SDNode*> Visited;
1357 EmitBaseThenIndex = false;
1358 // If Base ends up pointing to Index, we must emit index first. This is
1359 // because of the way we fold loads, we may end up doing bad things with
1361 if (NodeTransitivelyUsesValue(IAM.IndexReg, IAM.Base.Reg, Visited))
1362 EmitBaseThenIndex = true;
1365 if (EmitBaseThenIndex) {
1366 Result.Base.Reg = SelectExpr(IAM.Base.Reg);
1367 Result.IndexReg = SelectExpr(IAM.IndexReg);
1369 Result.IndexReg = SelectExpr(IAM.IndexReg);
1370 Result.Base.Reg = SelectExpr(IAM.Base.Reg);
1373 } else if (IAM.BaseType == X86ISelAddressMode::RegBase && IAM.Base.Reg.Val) {
1374 Result.Base.Reg = SelectExpr(IAM.Base.Reg);
1375 } else if (IAM.IndexReg.Val) {
1376 Result.IndexReg = SelectExpr(IAM.IndexReg);
1379 switch (IAM.BaseType) {
1380 case X86ISelAddressMode::RegBase:
1381 Result.BaseType = X86AddressMode::RegBase;
1383 case X86ISelAddressMode::FrameIndexBase:
1384 Result.BaseType = X86AddressMode::FrameIndexBase;
1385 Result.Base.FrameIndex = IAM.Base.FrameIndex;
1388 assert(0 && "Unknown base type!");
1391 Result.Scale = IAM.Scale;
1392 Result.Disp = IAM.Disp;
1397 /// SelectAddress - Pattern match the maximal addressing mode for this node and
1398 /// emit all of the leaf registers.
1399 void ISel::SelectAddress(SDOperand N, X86AddressMode &AM) {
1400 X86ISelAddressMode IAM;
1401 MatchAddress(N, IAM);
1402 AM = SelectAddrExprs(IAM);
1405 /// MatchAddress - Add the specified node to the specified addressing mode,
1406 /// returning true if it cannot be done. This just pattern matches for the
1407 /// addressing mode, it does not cause any code to be emitted. For that, use
1409 bool ISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM) {
1410 switch (N.getOpcode()) {
1412 case ISD::FrameIndex:
1413 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
1414 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
1415 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
1419 case ISD::GlobalAddress:
1421 GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
1422 // For Darwin, external and weak symbols are indirect, so we want to load
1423 // the value at address GV, not the value of GV itself. This means that
1424 // the GlobalAddress must be in the base or index register of the address,
1425 // not the GV offset field.
1426 if (Subtarget->getIndirectExternAndWeakGlobals() &&
1427 (GV->hasWeakLinkage() || GV->isExternal())) {
1436 AM.Disp += cast<ConstantSDNode>(N)->getValue();
1439 // We might have folded the load into this shift, so don't regen the value
1441 if (ExprMap.count(N)) break;
1443 if (AM.IndexReg.Val == 0 && AM.Scale == 1)
1444 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
1445 unsigned Val = CN->getValue();
1446 if (Val == 1 || Val == 2 || Val == 3) {
1447 AM.Scale = 1 << Val;
1448 SDOperand ShVal = N.Val->getOperand(0);
1450 // Okay, we know that we have a scale by now. However, if the scaled
1451 // value is an add of something and a constant, we can fold the
1452 // constant into the disp field here.
1453 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
1454 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
1455 AM.IndexReg = ShVal.Val->getOperand(0);
1456 ConstantSDNode *AddVal =
1457 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
1458 AM.Disp += AddVal->getValue() << Val;
1460 AM.IndexReg = ShVal;
1467 // We might have folded the load into this mul, so don't regen the value if
1469 if (ExprMap.count(N)) break;
1471 // X*[3,5,9] -> X+X*[2,4,8]
1472 if (AM.IndexReg.Val == 0 && AM.BaseType == X86ISelAddressMode::RegBase &&
1473 AM.Base.Reg.Val == 0)
1474 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
1475 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
1476 AM.Scale = unsigned(CN->getValue())-1;
1478 SDOperand MulVal = N.Val->getOperand(0);
1481 // Okay, we know that we have a scale by now. However, if the scaled
1482 // value is an add of something and a constant, we can fold the
1483 // constant into the disp field here.
1484 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1485 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
1486 Reg = MulVal.Val->getOperand(0);
1487 ConstantSDNode *AddVal =
1488 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
1489 AM.Disp += AddVal->getValue() * CN->getValue();
1491 Reg = N.Val->getOperand(0);
1494 AM.IndexReg = AM.Base.Reg = Reg;
1500 // We might have folded the load into this mul, so don't regen the value if
1502 if (ExprMap.count(N)) break;
1504 X86ISelAddressMode Backup = AM;
1505 if (!MatchAddress(N.Val->getOperand(0), AM) &&
1506 !MatchAddress(N.Val->getOperand(1), AM))
1509 if (!MatchAddress(N.Val->getOperand(1), AM) &&
1510 !MatchAddress(N.Val->getOperand(0), AM))
1517 // Is the base register already occupied?
1518 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
1519 // If so, check to see if the scale index register is set.
1520 if (AM.IndexReg.Val == 0) {
1526 // Otherwise, we cannot select it.
1530 // Default, generate it as a register.
1531 AM.BaseType = X86ISelAddressMode::RegBase;
1536 /// Emit2SetCCsAndLogical - Emit the following sequence of instructions,
1537 /// assuming that the temporary registers are in the 8-bit register class.
1541 /// DestReg = logicalop Tmp1, Tmp2
1543 static void Emit2SetCCsAndLogical(MachineBasicBlock *BB, unsigned SetCC1,
1544 unsigned SetCC2, unsigned LogicalOp,
1546 SSARegMap *RegMap = BB->getParent()->getSSARegMap();
1547 unsigned Tmp1 = RegMap->createVirtualRegister(X86::R8RegisterClass);
1548 unsigned Tmp2 = RegMap->createVirtualRegister(X86::R8RegisterClass);
1549 BuildMI(BB, SetCC1, 0, Tmp1);
1550 BuildMI(BB, SetCC2, 0, Tmp2);
1551 BuildMI(BB, LogicalOp, 2, DestReg).addReg(Tmp1).addReg(Tmp2);
1554 /// EmitSetCC - Emit the code to set the specified 8-bit register to 1 if the
1555 /// condition codes match the specified SetCCOpcode. Note that some conditions
1556 /// require multiple instructions to generate the correct value.
1557 static void EmitSetCC(MachineBasicBlock *BB, unsigned DestReg,
1558 ISD::CondCode SetCCOpcode, bool isFP) {
1561 switch (SetCCOpcode) {
1562 default: assert(0 && "Illegal integer SetCC!");
1563 case ISD::SETEQ: Opc = X86::SETEr; break;
1564 case ISD::SETGT: Opc = X86::SETGr; break;
1565 case ISD::SETGE: Opc = X86::SETGEr; break;
1566 case ISD::SETLT: Opc = X86::SETLr; break;
1567 case ISD::SETLE: Opc = X86::SETLEr; break;
1568 case ISD::SETNE: Opc = X86::SETNEr; break;
1569 case ISD::SETULT: Opc = X86::SETBr; break;
1570 case ISD::SETUGT: Opc = X86::SETAr; break;
1571 case ISD::SETULE: Opc = X86::SETBEr; break;
1572 case ISD::SETUGE: Opc = X86::SETAEr; break;
1575 // On a floating point condition, the flags are set as follows:
1577 // 0 | 0 | 0 | X > Y
1578 // 0 | 0 | 1 | X < Y
1579 // 1 | 0 | 0 | X == Y
1580 // 1 | 1 | 1 | unordered
1582 switch (SetCCOpcode) {
1583 default: assert(0 && "Invalid FP setcc!");
1586 Opc = X86::SETEr; // True if ZF = 1
1590 Opc = X86::SETAr; // True if CF = 0 and ZF = 0
1594 Opc = X86::SETAEr; // True if CF = 0
1598 Opc = X86::SETBr; // True if CF = 1
1602 Opc = X86::SETBEr; // True if CF = 1 or ZF = 1
1606 Opc = X86::SETNEr; // True if ZF = 0
1609 Opc = X86::SETPr; // True if PF = 1
1612 Opc = X86::SETNPr; // True if PF = 0
1614 case ISD::SETOEQ: // !PF & ZF
1615 Emit2SetCCsAndLogical(BB, X86::SETNPr, X86::SETEr, X86::AND8rr, DestReg);
1617 case ISD::SETOLT: // !PF & CF
1618 Emit2SetCCsAndLogical(BB, X86::SETNPr, X86::SETBr, X86::AND8rr, DestReg);
1620 case ISD::SETOLE: // !PF & (CF || ZF)
1621 Emit2SetCCsAndLogical(BB, X86::SETNPr, X86::SETBEr, X86::AND8rr, DestReg);
1623 case ISD::SETUGT: // PF | (!ZF & !CF)
1624 Emit2SetCCsAndLogical(BB, X86::SETPr, X86::SETAr, X86::OR8rr, DestReg);
1626 case ISD::SETUGE: // PF | !CF
1627 Emit2SetCCsAndLogical(BB, X86::SETPr, X86::SETAEr, X86::OR8rr, DestReg);
1629 case ISD::SETUNE: // PF | !ZF
1630 Emit2SetCCsAndLogical(BB, X86::SETPr, X86::SETNEr, X86::OR8rr, DestReg);
1634 BuildMI(BB, Opc, 0, DestReg);
1638 /// EmitBranchCC - Emit code into BB that arranges for control to transfer to
1639 /// the Dest block if the Cond condition is true. If we cannot fold this
1640 /// condition into the branch, return true.
1642 bool ISel::EmitBranchCC(MachineBasicBlock *Dest, SDOperand Chain,
1644 // FIXME: Evaluate whether it would be good to emit code like (X < Y) | (A >
1645 // B) using two conditional branches instead of one condbr, two setcc's, and
1647 if ((Cond.getOpcode() == ISD::OR ||
1648 Cond.getOpcode() == ISD::AND) && Cond.Val->hasOneUse()) {
1649 // And and or set the flags for us, so there is no need to emit a TST of the
1650 // result. It is only safe to do this if there is only a single use of the
1651 // AND/OR though, otherwise we don't know it will be emitted here.
1654 BuildMI(BB, X86::JNE, 1).addMBB(Dest);
1658 // Codegen br not C -> JE.
1659 if (Cond.getOpcode() == ISD::XOR)
1660 if (ConstantSDNode *NC = dyn_cast<ConstantSDNode>(Cond.Val->getOperand(1)))
1661 if (NC->isAllOnesValue()) {
1663 if (getRegPressure(Chain) > getRegPressure(Cond)) {
1665 CondR = SelectExpr(Cond.Val->getOperand(0));
1667 CondR = SelectExpr(Cond.Val->getOperand(0));
1670 BuildMI(BB, X86::TEST8rr, 2).addReg(CondR).addReg(CondR);
1671 BuildMI(BB, X86::JE, 1).addMBB(Dest);
1675 if (Cond.getOpcode() != ISD::SETCC)
1676 return true; // Can only handle simple setcc's so far.
1677 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
1681 // Handle integer conditions first.
1682 if (MVT::isInteger(Cond.getOperand(0).getValueType())) {
1684 default: assert(0 && "Illegal integer SetCC!");
1685 case ISD::SETEQ: Opc = X86::JE; break;
1686 case ISD::SETGT: Opc = X86::JG; break;
1687 case ISD::SETGE: Opc = X86::JGE; break;
1688 case ISD::SETLT: Opc = X86::JL; break;
1689 case ISD::SETLE: Opc = X86::JLE; break;
1690 case ISD::SETNE: Opc = X86::JNE; break;
1691 case ISD::SETULT: Opc = X86::JB; break;
1692 case ISD::SETUGT: Opc = X86::JA; break;
1693 case ISD::SETULE: Opc = X86::JBE; break;
1694 case ISD::SETUGE: Opc = X86::JAE; break;
1697 EmitCMP(Cond.getOperand(0), Cond.getOperand(1), Cond.hasOneUse());
1698 BuildMI(BB, Opc, 1).addMBB(Dest);
1702 unsigned Opc2 = 0; // Second branch if needed.
1704 // On a floating point condition, the flags are set as follows:
1706 // 0 | 0 | 0 | X > Y
1707 // 0 | 0 | 1 | X < Y
1708 // 1 | 0 | 0 | X == Y
1709 // 1 | 1 | 1 | unordered
1712 default: assert(0 && "Invalid FP setcc!");
1714 case ISD::SETEQ: Opc = X86::JE; break; // True if ZF = 1
1716 case ISD::SETGT: Opc = X86::JA; break; // True if CF = 0 and ZF = 0
1718 case ISD::SETGE: Opc = X86::JAE; break; // True if CF = 0
1720 case ISD::SETLT: Opc = X86::JB; break; // True if CF = 1
1722 case ISD::SETLE: Opc = X86::JBE; break; // True if CF = 1 or ZF = 1
1724 case ISD::SETNE: Opc = X86::JNE; break; // True if ZF = 0
1725 case ISD::SETUO: Opc = X86::JP; break; // True if PF = 1
1726 case ISD::SETO: Opc = X86::JNP; break; // True if PF = 0
1727 case ISD::SETUGT: // PF = 1 | (ZF = 0 & CF = 0)
1728 Opc = X86::JA; // ZF = 0 & CF = 0
1729 Opc2 = X86::JP; // PF = 1
1731 case ISD::SETUGE: // PF = 1 | CF = 0
1732 Opc = X86::JAE; // CF = 0
1733 Opc2 = X86::JP; // PF = 1
1735 case ISD::SETUNE: // PF = 1 | ZF = 0
1736 Opc = X86::JNE; // ZF = 0
1737 Opc2 = X86::JP; // PF = 1
1739 case ISD::SETOEQ: // PF = 0 & ZF = 1
1742 return true; // FIXME: Emit more efficient code for this branch.
1743 case ISD::SETOLT: // PF = 0 & CF = 1
1746 return true; // FIXME: Emit more efficient code for this branch.
1747 case ISD::SETOLE: // PF = 0 & (CF = 1 || ZF = 1)
1748 //X86::JNP, X86::JBE
1750 return true; // FIXME: Emit more efficient code for this branch.
1754 EmitCMP(Cond.getOperand(0), Cond.getOperand(1), Cond.hasOneUse());
1755 BuildMI(BB, Opc, 1).addMBB(Dest);
1757 BuildMI(BB, Opc2, 1).addMBB(Dest);
1761 /// EmitSelectCC - Emit code into BB that performs a select operation between
1762 /// the two registers RTrue and RFalse, generating a result into RDest.
1764 void ISel::EmitSelectCC(SDOperand Cond, SDOperand True, SDOperand False,
1765 MVT::ValueType SVT, unsigned RDest) {
1766 unsigned RTrue, RFalse;
1768 EQ, NE, LT, LE, GT, GE, B, BE, A, AE, P, NP,
1770 } CondCode = NOT_SET;
1772 static const unsigned CMOVTAB16[] = {
1773 X86::CMOVE16rr, X86::CMOVNE16rr, X86::CMOVL16rr, X86::CMOVLE16rr,
1774 X86::CMOVG16rr, X86::CMOVGE16rr, X86::CMOVB16rr, X86::CMOVBE16rr,
1775 X86::CMOVA16rr, X86::CMOVAE16rr, X86::CMOVP16rr, X86::CMOVNP16rr,
1777 static const unsigned CMOVTAB32[] = {
1778 X86::CMOVE32rr, X86::CMOVNE32rr, X86::CMOVL32rr, X86::CMOVLE32rr,
1779 X86::CMOVG32rr, X86::CMOVGE32rr, X86::CMOVB32rr, X86::CMOVBE32rr,
1780 X86::CMOVA32rr, X86::CMOVAE32rr, X86::CMOVP32rr, X86::CMOVNP32rr,
1782 static const unsigned CMOVTABFP[] = {
1783 X86::FCMOVE , X86::FCMOVNE, /*missing*/0, /*missing*/0,
1784 /*missing*/0, /*missing*/0, X86::FCMOVB , X86::FCMOVBE,
1785 X86::FCMOVA , X86::FCMOVAE, X86::FCMOVP , X86::FCMOVNP
1787 static const int SSE_CMOVTAB[] = {
1788 /*CMPEQ*/ 0, /*CMPNEQ*/ 4, /*missing*/ 0, /*missing*/ 0,
1789 /*missing*/ 0, /*missing*/ 0, /*CMPLT*/ 1, /*CMPLE*/ 2,
1790 /*CMPNLE*/ 6, /*CMPNLT*/ 5, /*CMPUNORD*/ 3, /*CMPORD*/ 7
1793 if (Cond.getOpcode() == ISD::SETCC) {
1794 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
1795 if (MVT::isInteger(Cond.getOperand(0).getValueType())) {
1797 default: assert(0 && "Unknown integer comparison!");
1798 case ISD::SETEQ: CondCode = EQ; break;
1799 case ISD::SETGT: CondCode = GT; break;
1800 case ISD::SETGE: CondCode = GE; break;
1801 case ISD::SETLT: CondCode = LT; break;
1802 case ISD::SETLE: CondCode = LE; break;
1803 case ISD::SETNE: CondCode = NE; break;
1804 case ISD::SETULT: CondCode = B; break;
1805 case ISD::SETUGT: CondCode = A; break;
1806 case ISD::SETULE: CondCode = BE; break;
1807 case ISD::SETUGE: CondCode = AE; break;
1810 // On a floating point condition, the flags are set as follows:
1812 // 0 | 0 | 0 | X > Y
1813 // 0 | 0 | 1 | X < Y
1814 // 1 | 0 | 0 | X == Y
1815 // 1 | 1 | 1 | unordered
1818 default: assert(0 && "Unknown FP comparison!");
1820 case ISD::SETEQ: CondCode = EQ; break; // True if ZF = 1
1822 case ISD::SETGT: CondCode = A; break; // True if CF = 0 and ZF = 0
1824 case ISD::SETGE: CondCode = AE; break; // True if CF = 0
1826 case ISD::SETLT: CondCode = B; break; // True if CF = 1
1828 case ISD::SETLE: CondCode = BE; break; // True if CF = 1 or ZF = 1
1830 case ISD::SETNE: CondCode = NE; break; // True if ZF = 0
1831 case ISD::SETUO: CondCode = P; break; // True if PF = 1
1832 case ISD::SETO: CondCode = NP; break; // True if PF = 0
1833 case ISD::SETUGT: // PF = 1 | (ZF = 0 & CF = 0)
1834 case ISD::SETUGE: // PF = 1 | CF = 0
1835 case ISD::SETUNE: // PF = 1 | ZF = 0
1836 case ISD::SETOEQ: // PF = 0 & ZF = 1
1837 case ISD::SETOLT: // PF = 0 & CF = 1
1838 case ISD::SETOLE: // PF = 0 & (CF = 1 || ZF = 1)
1839 // We cannot emit this comparison as a single cmov.
1845 // There's no SSE equivalent of FCMOVE. For cases where we set a condition
1846 // code above and one of the results of the select is +0.0, then we can fake
1847 // it up through a clever AND with mask. Otherwise, we will fall through to
1848 // the code below that will use a PHI node to select the right value.
1849 if (X86ScalarSSE && (SVT == MVT::f32 || SVT == MVT::f64)) {
1850 if (Cond.getOperand(0).getValueType() == SVT &&
1851 NOT_SET != CondCode) {
1852 ConstantFPSDNode *CT = dyn_cast<ConstantFPSDNode>(True);
1853 ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(False);
1854 bool TrueZero = CT && CT->isExactlyValue(0.0);
1855 bool FalseZero = CF && CF->isExactlyValue(0.0);
1856 if (TrueZero || FalseZero) {
1857 SDOperand LHS = Cond.getOperand(0);
1858 SDOperand RHS = Cond.getOperand(1);
1860 // Select the two halves of the condition
1861 unsigned RLHS, RRHS;
1862 if (getRegPressure(LHS) > getRegPressure(RHS)) {
1863 RLHS = SelectExpr(LHS);
1864 RRHS = SelectExpr(RHS);
1866 RRHS = SelectExpr(RHS);
1867 RLHS = SelectExpr(LHS);
1870 // Emit the comparison and generate a mask from it
1871 unsigned MaskReg = MakeReg(SVT);
1872 unsigned Opc = (SVT == MVT::f32) ? X86::CMPSSrr : X86::CMPSDrr;
1873 BuildMI(BB, Opc, 3, MaskReg).addReg(RLHS).addReg(RRHS)
1874 .addImm(SSE_CMOVTAB[CondCode]);
1877 RFalse = SelectExpr(False);
1878 Opc = (SVT == MVT::f32) ? X86::ANDNPSrr : X86::ANDNPDrr;
1879 BuildMI(BB, Opc, 2, RDest).addReg(MaskReg).addReg(RFalse);
1881 RTrue = SelectExpr(True);
1882 Opc = (SVT == MVT::f32) ? X86::ANDPSrr : X86::ANDPDrr;
1883 BuildMI(BB, Opc, 2, RDest).addReg(MaskReg).addReg(RTrue);
1891 // Select the true and false values for use in both the SSE PHI case, and the
1892 // integer or x87 cmov cases below.
1893 if (getRegPressure(True) > getRegPressure(False)) {
1894 RTrue = SelectExpr(True);
1895 RFalse = SelectExpr(False);
1897 RFalse = SelectExpr(False);
1898 RTrue = SelectExpr(True);
1901 // Since there's no SSE equivalent of FCMOVE, and we couldn't generate an
1902 // AND with mask, we'll have to do the normal RISC thing and generate a PHI
1903 // node to select between the true and false values.
1904 if (X86ScalarSSE && (SVT == MVT::f32 || SVT == MVT::f64)) {
1905 // FIXME: emit a direct compare and branch rather than setting a cond reg
1907 unsigned CondReg = SelectExpr(Cond);
1908 BuildMI(BB, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1910 // Create an iterator with which to insert the MBB for copying the false
1911 // value and the MBB to hold the PHI instruction for this SetCC.
1912 MachineBasicBlock *thisMBB = BB;
1913 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1914 ilist<MachineBasicBlock>::iterator It = BB;
1920 // cmpTY ccX, r1, r2
1922 // fallthrough --> copy0MBB
1923 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1924 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1925 BuildMI(BB, X86::JNE, 1).addMBB(sinkMBB);
1926 MachineFunction *F = BB->getParent();
1927 F->getBasicBlockList().insert(It, copy0MBB);
1928 F->getBasicBlockList().insert(It, sinkMBB);
1929 // Update machine-CFG edges
1930 BB->addSuccessor(copy0MBB);
1931 BB->addSuccessor(sinkMBB);
1934 // %FalseValue = ...
1935 // # fallthrough to sinkMBB
1937 // Update machine-CFG edges
1938 BB->addSuccessor(sinkMBB);
1941 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1944 BuildMI(BB, X86::PHI, 4, RDest).addReg(RFalse)
1945 .addMBB(copy0MBB).addReg(RTrue).addMBB(thisMBB);
1950 if (CondCode != NOT_SET) {
1952 default: assert(0 && "Cannot select this type!");
1953 case MVT::i16: Opc = CMOVTAB16[CondCode]; break;
1954 case MVT::i32: Opc = CMOVTAB32[CondCode]; break;
1955 case MVT::f64: Opc = CMOVTABFP[CondCode]; break;
1959 // Finally, if we weren't able to fold this, just emit the condition and test
1961 if (CondCode == NOT_SET || Opc == 0) {
1962 // Get the condition into the zero flag.
1963 unsigned CondReg = SelectExpr(Cond);
1964 BuildMI(BB, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1967 default: assert(0 && "Cannot select this type!");
1968 case MVT::i16: Opc = X86::CMOVE16rr; break;
1969 case MVT::i32: Opc = X86::CMOVE32rr; break;
1970 case MVT::f64: Opc = X86::FCMOVE; break;
1973 // FIXME: CMP R, 0 -> TEST R, R
1974 EmitCMP(Cond.getOperand(0), Cond.getOperand(1), Cond.Val->hasOneUse());
1975 std::swap(RTrue, RFalse);
1977 BuildMI(BB, Opc, 2, RDest).addReg(RTrue).addReg(RFalse);
1980 void ISel::EmitCMP(SDOperand LHS, SDOperand RHS, bool HasOneUse) {
1982 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
1984 if (HasOneUse && isFoldableLoad(LHS, RHS)) {
1985 switch (RHS.getValueType()) {
1988 case MVT::i8: Opc = X86::CMP8mi; break;
1989 case MVT::i16: Opc = X86::CMP16mi; break;
1990 case MVT::i32: Opc = X86::CMP32mi; break;
1994 EmitFoldedLoad(LHS, AM);
1995 addFullAddress(BuildMI(BB, Opc, 5), AM).addImm(CN->getValue());
2000 switch (RHS.getValueType()) {
2003 case MVT::i8: Opc = X86::CMP8ri; break;
2004 case MVT::i16: Opc = X86::CMP16ri; break;
2005 case MVT::i32: Opc = X86::CMP32ri; break;
2008 unsigned Tmp1 = SelectExpr(LHS);
2009 BuildMI(BB, Opc, 2).addReg(Tmp1).addImm(CN->getValue());
2012 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(RHS)) {
2013 if (!X86ScalarSSE && (CN->isExactlyValue(+0.0) ||
2014 CN->isExactlyValue(-0.0))) {
2015 unsigned Reg = SelectExpr(LHS);
2016 BuildMI(BB, X86::FTST, 1).addReg(Reg);
2017 BuildMI(BB, X86::FNSTSW8r, 0);
2018 BuildMI(BB, X86::SAHF, 1);
2024 if (HasOneUse && isFoldableLoad(LHS, RHS)) {
2025 switch (RHS.getValueType()) {
2028 case MVT::i8: Opc = X86::CMP8mr; break;
2029 case MVT::i16: Opc = X86::CMP16mr; break;
2030 case MVT::i32: Opc = X86::CMP32mr; break;
2034 EmitFoldedLoad(LHS, AM);
2035 unsigned Reg = SelectExpr(RHS);
2036 addFullAddress(BuildMI(BB, Opc, 5), AM).addReg(Reg);
2041 switch (LHS.getValueType()) {
2042 default: assert(0 && "Cannot compare this value!");
2044 case MVT::i8: Opc = X86::CMP8rr; break;
2045 case MVT::i16: Opc = X86::CMP16rr; break;
2046 case MVT::i32: Opc = X86::CMP32rr; break;
2047 case MVT::f32: Opc = X86::UCOMISSrr; break;
2048 case MVT::f64: Opc = X86ScalarSSE ? X86::UCOMISDrr : X86::FUCOMIr; break;
2050 unsigned Tmp1, Tmp2;
2051 if (getRegPressure(LHS) > getRegPressure(RHS)) {
2052 Tmp1 = SelectExpr(LHS);
2053 Tmp2 = SelectExpr(RHS);
2055 Tmp2 = SelectExpr(RHS);
2056 Tmp1 = SelectExpr(LHS);
2058 BuildMI(BB, Opc, 2).addReg(Tmp1).addReg(Tmp2);
2061 /// isFoldableLoad - Return true if this is a load instruction that can safely
2062 /// be folded into an operation that uses it.
2063 bool ISel::isFoldableLoad(SDOperand Op, SDOperand OtherOp, bool FloatPromoteOk){
2064 if (Op.getOpcode() == ISD::LOAD) {
2065 // FIXME: currently can't fold constant pool indexes.
2066 if (isa<ConstantPoolSDNode>(Op.getOperand(1)))
2068 } else if (FloatPromoteOk && Op.getOpcode() == ISD::EXTLOAD &&
2069 cast<VTSDNode>(Op.getOperand(3))->getVT() == MVT::f32) {
2070 // FIXME: currently can't fold constant pool indexes.
2071 if (isa<ConstantPoolSDNode>(Op.getOperand(1)))
2077 // If this load has already been emitted, we clearly can't fold it.
2078 assert(Op.ResNo == 0 && "Not a use of the value of the load?");
2079 if (ExprMap.count(Op.getValue(1))) return false;
2080 assert(!ExprMap.count(Op.getValue(0)) && "Value in map but not token chain?");
2081 assert(!ExprMap.count(Op.getValue(1))&&"Token lowered but value not in map?");
2083 // If there is not just one use of its value, we cannot fold.
2084 if (!Op.Val->hasNUsesOfValue(1, 0)) return false;
2086 // Finally, we cannot fold the load into the operation if this would induce a
2087 // cycle into the resultant dag. To check for this, see if OtherOp (the other
2088 // operand of the operation we are folding the load into) can possible use the
2089 // chain node defined by the load.
2090 if (OtherOp.Val && !Op.Val->hasNUsesOfValue(0, 1)) { // Has uses of chain?
2091 std::set<SDNode*> Visited;
2092 if (NodeTransitivelyUsesValue(OtherOp, Op.getValue(1), Visited))
2099 /// EmitFoldedLoad - Ensure that the arguments of the load are code generated,
2100 /// and compute the address being loaded into AM.
2101 void ISel::EmitFoldedLoad(SDOperand Op, X86AddressMode &AM) {
2102 SDOperand Chain = Op.getOperand(0);
2103 SDOperand Address = Op.getOperand(1);
2105 if (getRegPressure(Chain) > getRegPressure(Address)) {
2107 SelectAddress(Address, AM);
2109 SelectAddress(Address, AM);
2113 // The chain for this load is now lowered.
2114 assert(ExprMap.count(SDOperand(Op.Val, 1)) == 0 &&
2115 "Load emitted more than once?");
2116 if (!ExprMap.insert(std::make_pair(Op.getValue(1), 1)).second)
2117 assert(0 && "Load emitted more than once!");
2120 // EmitOrOpOp - Pattern match the expression (Op1|Op2), where we know that op1
2121 // and op2 are i8/i16/i32 values with one use each (the or). If we can form a
2122 // SHLD or SHRD, emit the instruction (generating the value into DestReg) and
2124 bool ISel::EmitOrOpOp(SDOperand Op1, SDOperand Op2, unsigned DestReg) {
2125 if (Op1.getOpcode() == ISD::SHL && Op2.getOpcode() == ISD::SRL) {
2127 } else if (Op2.getOpcode() == ISD::SHL && Op1.getOpcode() == ISD::SRL) {
2128 std::swap(Op1, Op2); // Op1 is the SHL now.
2130 return false; // No match
2133 SDOperand ShlVal = Op1.getOperand(0);
2134 SDOperand ShlAmt = Op1.getOperand(1);
2135 SDOperand ShrVal = Op2.getOperand(0);
2136 SDOperand ShrAmt = Op2.getOperand(1);
2138 unsigned RegSize = MVT::getSizeInBits(Op1.getValueType());
2140 // Find out if ShrAmt = 32-ShlAmt or ShlAmt = 32-ShrAmt.
2141 if (ShlAmt.getOpcode() == ISD::SUB && ShlAmt.getOperand(1) == ShrAmt)
2142 if (ConstantSDNode *SubCST = dyn_cast<ConstantSDNode>(ShlAmt.getOperand(0)))
2143 if (SubCST->getValue() == RegSize) {
2144 // (A >> ShrAmt) | (A << (32-ShrAmt)) ==> ROR A, ShrAmt
2145 // (A >> ShrAmt) | (B << (32-ShrAmt)) ==> SHRD A, B, ShrAmt
2146 if (ShrVal == ShlVal) {
2147 unsigned Reg, ShAmt;
2148 if (getRegPressure(ShrVal) > getRegPressure(ShrAmt)) {
2149 Reg = SelectExpr(ShrVal);
2150 ShAmt = SelectExpr(ShrAmt);
2152 ShAmt = SelectExpr(ShrAmt);
2153 Reg = SelectExpr(ShrVal);
2155 BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShAmt);
2156 unsigned Opc = RegSize == 8 ? X86::ROR8rCL :
2157 (RegSize == 16 ? X86::ROR16rCL : X86::ROR32rCL);
2158 BuildMI(BB, Opc, 1, DestReg).addReg(Reg);
2160 } else if (RegSize != 8) {
2161 unsigned AReg, BReg;
2162 if (getRegPressure(ShlVal) > getRegPressure(ShrVal)) {
2163 BReg = SelectExpr(ShlVal);
2164 AReg = SelectExpr(ShrVal);
2166 AReg = SelectExpr(ShrVal);
2167 BReg = SelectExpr(ShlVal);
2169 unsigned ShAmt = SelectExpr(ShrAmt);
2170 BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShAmt);
2171 unsigned Opc = RegSize == 16 ? X86::SHRD16rrCL : X86::SHRD32rrCL;
2172 BuildMI(BB, Opc, 2, DestReg).addReg(AReg).addReg(BReg);
2177 if (ShrAmt.getOpcode() == ISD::SUB && ShrAmt.getOperand(1) == ShlAmt)
2178 if (ConstantSDNode *SubCST = dyn_cast<ConstantSDNode>(ShrAmt.getOperand(0)))
2179 if (SubCST->getValue() == RegSize) {
2180 // (A << ShlAmt) | (A >> (32-ShlAmt)) ==> ROL A, ShrAmt
2181 // (A << ShlAmt) | (B >> (32-ShlAmt)) ==> SHLD A, B, ShrAmt
2182 if (ShrVal == ShlVal) {
2183 unsigned Reg, ShAmt;
2184 if (getRegPressure(ShrVal) > getRegPressure(ShlAmt)) {
2185 Reg = SelectExpr(ShrVal);
2186 ShAmt = SelectExpr(ShlAmt);
2188 ShAmt = SelectExpr(ShlAmt);
2189 Reg = SelectExpr(ShrVal);
2191 BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShAmt);
2192 unsigned Opc = RegSize == 8 ? X86::ROL8rCL :
2193 (RegSize == 16 ? X86::ROL16rCL : X86::ROL32rCL);
2194 BuildMI(BB, Opc, 1, DestReg).addReg(Reg);
2196 } else if (RegSize != 8) {
2197 unsigned AReg, BReg;
2198 if (getRegPressure(ShlVal) > getRegPressure(ShrVal)) {
2199 AReg = SelectExpr(ShlVal);
2200 BReg = SelectExpr(ShrVal);
2202 BReg = SelectExpr(ShrVal);
2203 AReg = SelectExpr(ShlVal);
2205 unsigned ShAmt = SelectExpr(ShlAmt);
2206 BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShAmt);
2207 unsigned Opc = RegSize == 16 ? X86::SHLD16rrCL : X86::SHLD32rrCL;
2208 BuildMI(BB, Opc, 2, DestReg).addReg(AReg).addReg(BReg);
2213 if (ConstantSDNode *ShrCst = dyn_cast<ConstantSDNode>(ShrAmt))
2214 if (ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(ShlAmt))
2215 if (ShrCst->getValue() < RegSize && ShlCst->getValue() < RegSize)
2216 if (ShrCst->getValue() == RegSize-ShlCst->getValue()) {
2217 // (A >> 5) | (A << 27) --> ROR A, 5
2218 // (A >> 5) | (B << 27) --> SHRD A, B, 5
2219 if (ShrVal == ShlVal) {
2220 unsigned Reg = SelectExpr(ShrVal);
2221 unsigned Opc = RegSize == 8 ? X86::ROR8ri :
2222 (RegSize == 16 ? X86::ROR16ri : X86::ROR32ri);
2223 BuildMI(BB, Opc, 2, DestReg).addReg(Reg).addImm(ShrCst->getValue());
2225 } else if (RegSize != 8) {
2226 unsigned AReg, BReg;
2227 if (getRegPressure(ShlVal) > getRegPressure(ShrVal)) {
2228 BReg = SelectExpr(ShlVal);
2229 AReg = SelectExpr(ShrVal);
2231 AReg = SelectExpr(ShrVal);
2232 BReg = SelectExpr(ShlVal);
2234 unsigned Opc = RegSize == 16 ? X86::SHRD16rri8 : X86::SHRD32rri8;
2235 BuildMI(BB, Opc, 3, DestReg).addReg(AReg).addReg(BReg)
2236 .addImm(ShrCst->getValue());
2244 unsigned ISel::SelectExpr(SDOperand N) {
2246 unsigned Tmp1, Tmp2, Tmp3;
2248 SDNode *Node = N.Val;
2251 if (Node->getOpcode() == ISD::CopyFromReg) {
2252 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
2253 // Just use the specified register as our input if we can.
2254 if (MRegisterInfo::isVirtualRegister(Reg) || Reg == X86::ESP)
2258 unsigned &Reg = ExprMap[N];
2259 if (Reg) return Reg;
2261 switch (N.getOpcode()) {
2263 Reg = Result = (N.getValueType() != MVT::Other) ?
2264 MakeReg(N.getValueType()) : 1;
2266 case X86ISD::TAILCALL:
2268 // If this is a call instruction, make sure to prepare ALL of the result
2269 // values as well as the chain.
2270 ExprMap[N.getValue(0)] = 1;
2271 if (Node->getNumValues() > 1) {
2272 Result = MakeReg(Node->getValueType(1));
2273 ExprMap[N.getValue(1)] = Result;
2274 for (unsigned i = 2, e = Node->getNumValues(); i != e; ++i)
2275 ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
2280 case ISD::ADD_PARTS:
2281 case ISD::SUB_PARTS:
2282 case ISD::SHL_PARTS:
2283 case ISD::SRL_PARTS:
2284 case ISD::SRA_PARTS:
2285 Result = MakeReg(Node->getValueType(0));
2286 ExprMap[N.getValue(0)] = Result;
2287 for (unsigned i = 1, e = N.Val->getNumValues(); i != e; ++i)
2288 ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
2292 switch (N.getOpcode()) {
2295 assert(0 && "Node not handled!\n");
2296 case ISD::FP_EXTEND:
2297 assert(X86ScalarSSE && "Scalar SSE FP must be enabled to use f32");
2298 Tmp1 = SelectExpr(N.getOperand(0));
2299 BuildMI(BB, X86::CVTSS2SDrr, 1, Result).addReg(Tmp1);
2302 assert(X86ScalarSSE && "Scalar SSE FP must be enabled to use f32");
2303 Tmp1 = SelectExpr(N.getOperand(0));
2304 BuildMI(BB, X86::CVTSD2SSrr, 1, Result).addReg(Tmp1);
2306 case ISD::CopyFromReg:
2307 Select(N.getOperand(0));
2309 Reg = Result = ExprMap[N.getValue(0)] =
2310 MakeReg(N.getValue(0).getValueType());
2312 Tmp1 = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
2313 switch (Node->getValueType(0)) {
2314 default: assert(0 && "Cannot CopyFromReg this!");
2317 BuildMI(BB, X86::MOV8rr, 1, Result).addReg(Tmp1);
2320 BuildMI(BB, X86::MOV16rr, 1, Result).addReg(Tmp1);
2323 BuildMI(BB, X86::MOV32rr, 1, Result).addReg(Tmp1);
2327 case ISD::FrameIndex:
2328 Tmp1 = cast<FrameIndexSDNode>(N)->getIndex();
2329 addFrameReference(BuildMI(BB, X86::LEA32r, 4, Result), (int)Tmp1);
2331 case ISD::ConstantPool:
2332 Tmp1 = cast<ConstantPoolSDNode>(N)->getIndex();
2333 addConstantPoolReference(BuildMI(BB, X86::LEA32r, 4, Result), Tmp1);
2335 case ISD::ConstantFP:
2337 assert(cast<ConstantFPSDNode>(N)->isExactlyValue(+0.0) &&
2338 "SSE only supports +0.0");
2339 Opc = (N.getValueType() == MVT::f32) ? X86::FLD0SS : X86::FLD0SD;
2340 BuildMI(BB, Opc, 0, Result);
2343 ContainsFPCode = true;
2344 Tmp1 = Result; // Intermediate Register
2345 if (cast<ConstantFPSDNode>(N)->getValue() < 0.0 ||
2346 cast<ConstantFPSDNode>(N)->isExactlyValue(-0.0))
2347 Tmp1 = MakeReg(MVT::f64);
2349 if (cast<ConstantFPSDNode>(N)->isExactlyValue(+0.0) ||
2350 cast<ConstantFPSDNode>(N)->isExactlyValue(-0.0))
2351 BuildMI(BB, X86::FLD0, 0, Tmp1);
2352 else if (cast<ConstantFPSDNode>(N)->isExactlyValue(+1.0) ||
2353 cast<ConstantFPSDNode>(N)->isExactlyValue(-1.0))
2354 BuildMI(BB, X86::FLD1, 0, Tmp1);
2356 assert(0 && "Unexpected constant!");
2358 BuildMI(BB, X86::FCHS, 1, Result).addReg(Tmp1);
2361 switch (N.getValueType()) {
2362 default: assert(0 && "Cannot use constants of this type!");
2364 case MVT::i8: Opc = X86::MOV8ri; break;
2365 case MVT::i16: Opc = X86::MOV16ri; break;
2366 case MVT::i32: Opc = X86::MOV32ri; break;
2368 BuildMI(BB, Opc, 1,Result).addImm(cast<ConstantSDNode>(N)->getValue());
2371 if (Node->getValueType(0) == MVT::f64) {
2372 // FIXME: SHOULD TEACH STACKIFIER ABOUT UNDEF VALUES!
2373 BuildMI(BB, X86::FLD0, 0, Result);
2375 BuildMI(BB, X86::IMPLICIT_DEF, 0, Result);
2378 case ISD::GlobalAddress: {
2379 GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
2380 // For Darwin, external and weak symbols are indirect, so we want to load
2381 // the value at address GV, not the value of GV itself.
2382 if (Subtarget->getIndirectExternAndWeakGlobals() &&
2383 (GV->hasWeakLinkage() || GV->isExternal())) {
2384 BuildMI(BB, X86::MOV32rm, 4, Result).addReg(0).addZImm(1).addReg(0)
2385 .addGlobalAddress(GV, false, 0);
2387 BuildMI(BB, X86::MOV32ri, 1, Result).addGlobalAddress(GV);
2391 case ISD::ExternalSymbol: {
2392 const char *Sym = cast<ExternalSymbolSDNode>(N)->getSymbol();
2393 BuildMI(BB, X86::MOV32ri, 1, Result).addExternalSymbol(Sym);
2396 case ISD::ZERO_EXTEND: {
2397 int DestIs16 = N.getValueType() == MVT::i16;
2398 int SrcIs16 = N.getOperand(0).getValueType() == MVT::i16;
2400 // FIXME: This hack is here for zero extension casts from bool to i8. This
2401 // would not be needed if bools were promoted by Legalize.
2402 if (N.getValueType() == MVT::i8) {
2403 Tmp1 = SelectExpr(N.getOperand(0));
2404 BuildMI(BB, X86::MOV8rr, 1, Result).addReg(Tmp1);
2408 if (isFoldableLoad(N.getOperand(0), SDOperand())) {
2409 static const unsigned Opc[3] = {
2410 X86::MOVZX32rm8, X86::MOVZX32rm16, X86::MOVZX16rm8
2414 EmitFoldedLoad(N.getOperand(0), AM);
2415 addFullAddress(BuildMI(BB, Opc[SrcIs16+DestIs16*2], 4, Result), AM);
2420 static const unsigned Opc[3] = {
2421 X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOVZX16rr8
2423 Tmp1 = SelectExpr(N.getOperand(0));
2424 BuildMI(BB, Opc[SrcIs16+DestIs16*2], 1, Result).addReg(Tmp1);
2427 case ISD::SIGN_EXTEND: {
2428 int DestIs16 = N.getValueType() == MVT::i16;
2429 int SrcIs16 = N.getOperand(0).getValueType() == MVT::i16;
2431 // FIXME: Legalize should promote bools to i8!
2432 assert(N.getOperand(0).getValueType() != MVT::i1 &&
2433 "Sign extend from bool not implemented!");
2435 if (isFoldableLoad(N.getOperand(0), SDOperand())) {
2436 static const unsigned Opc[3] = {
2437 X86::MOVSX32rm8, X86::MOVSX32rm16, X86::MOVSX16rm8
2441 EmitFoldedLoad(N.getOperand(0), AM);
2442 addFullAddress(BuildMI(BB, Opc[SrcIs16+DestIs16*2], 4, Result), AM);
2446 static const unsigned Opc[3] = {
2447 X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOVSX16rr8
2449 Tmp1 = SelectExpr(N.getOperand(0));
2450 BuildMI(BB, Opc[SrcIs16+DestIs16*2], 1, Result).addReg(Tmp1);
2454 // Fold TRUNCATE (LOAD P) into a smaller load from P.
2455 // FIXME: This should be performed by the DAGCombiner.
2456 if (isFoldableLoad(N.getOperand(0), SDOperand())) {
2457 switch (N.getValueType()) {
2458 default: assert(0 && "Unknown truncate!");
2460 case MVT::i8: Opc = X86::MOV8rm; break;
2461 case MVT::i16: Opc = X86::MOV16rm; break;
2464 EmitFoldedLoad(N.getOperand(0), AM);
2465 addFullAddress(BuildMI(BB, Opc, 4, Result), AM);
2469 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by
2470 // a move out of AX or AL.
2471 switch (N.getOperand(0).getValueType()) {
2472 default: assert(0 && "Unknown truncate!");
2473 case MVT::i8: Tmp2 = X86::AL; Opc = X86::MOV8rr; break;
2474 case MVT::i16: Tmp2 = X86::AX; Opc = X86::MOV16rr; break;
2475 case MVT::i32: Tmp2 = X86::EAX; Opc = X86::MOV32rr; break;
2477 Tmp1 = SelectExpr(N.getOperand(0));
2478 BuildMI(BB, Opc, 1, Tmp2).addReg(Tmp1);
2480 switch (N.getValueType()) {
2481 default: assert(0 && "Unknown truncate!");
2483 case MVT::i8: Tmp2 = X86::AL; Opc = X86::MOV8rr; break;
2484 case MVT::i16: Tmp2 = X86::AX; Opc = X86::MOV16rr; break;
2486 BuildMI(BB, Opc, 1, Result).addReg(Tmp2);
2489 case ISD::SINT_TO_FP: {
2490 Tmp1 = SelectExpr(N.getOperand(0)); // Get the operand register
2491 unsigned PromoteOpcode = 0;
2493 // We can handle any sint to fp with the direct sse conversion instructions.
2495 Opc = (N.getValueType() == MVT::f64) ? X86::CVTSI2SDrr : X86::CVTSI2SSrr;
2496 BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2500 ContainsFPCode = true;
2502 // Spill the integer to memory and reload it from there.
2503 MVT::ValueType SrcTy = N.getOperand(0).getValueType();
2504 unsigned Size = MVT::getSizeInBits(SrcTy)/8;
2505 MachineFunction *F = BB->getParent();
2506 int FrameIdx = F->getFrameInfo()->CreateStackObject(Size, Size);
2510 addFrameReference(BuildMI(BB, X86::MOV32mr, 5), FrameIdx).addReg(Tmp1);
2511 addFrameReference(BuildMI(BB, X86::FILD32m, 5, Result), FrameIdx);
2514 addFrameReference(BuildMI(BB, X86::MOV16mr, 5), FrameIdx).addReg(Tmp1);
2515 addFrameReference(BuildMI(BB, X86::FILD16m, 5, Result), FrameIdx);
2517 default: break; // No promotion required.
2521 case ISD::FP_TO_SINT:
2522 Tmp1 = SelectExpr(N.getOperand(0)); // Get the operand register
2524 // If the target supports SSE2 and is performing FP operations in SSE regs
2525 // instead of the FP stack, then we can use the efficient CVTSS2SI and
2526 // CVTSD2SI instructions.
2527 assert(X86ScalarSSE);
2528 if (MVT::f32 == N.getOperand(0).getValueType()) {
2529 BuildMI(BB, X86::CVTTSS2SIrr, 1, Result).addReg(Tmp1);
2530 } else if (MVT::f64 == N.getOperand(0).getValueType()) {
2531 BuildMI(BB, X86::CVTTSD2SIrr, 1, Result).addReg(Tmp1);
2533 assert(0 && "Not an f32 or f64?");
2539 Op0 = N.getOperand(0);
2540 Op1 = N.getOperand(1);
2542 if (isFoldableLoad(Op0, Op1, true)) {
2543 std::swap(Op0, Op1);
2547 if (isFoldableLoad(Op1, Op0, true)) {
2549 switch (N.getValueType()) {
2550 default: assert(0 && "Cannot add this type!");
2552 case MVT::i8: Opc = X86::ADD8rm; break;
2553 case MVT::i16: Opc = X86::ADD16rm; break;
2554 case MVT::i32: Opc = X86::ADD32rm; break;
2555 case MVT::f32: Opc = X86::ADDSSrm; break;
2557 // For F64, handle promoted load operations (from F32) as well!
2559 assert(Op1.getOpcode() == ISD::LOAD && "SSE load not promoted");
2562 Opc = Op1.getOpcode() == ISD::LOAD ? X86::FADD64m : X86::FADD32m;
2567 EmitFoldedLoad(Op1, AM);
2568 Tmp1 = SelectExpr(Op0);
2569 addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
2573 // See if we can codegen this as an LEA to fold operations together.
2574 if (N.getValueType() == MVT::i32) {
2576 X86ISelAddressMode AM;
2577 MatchAddress(N, AM);
2578 ExprMap[N] = Result;
2580 // If this is not just an add, emit the LEA. For a simple add (like
2581 // reg+reg or reg+imm), we just emit an add. It might be a good idea to
2582 // leave this as LEA, then peephole it to 'ADD' after two address elim
2584 if (AM.Scale != 1 || AM.BaseType == X86ISelAddressMode::FrameIndexBase||
2585 AM.GV || (AM.Base.Reg.Val && AM.IndexReg.Val && AM.Disp)) {
2586 X86AddressMode XAM = SelectAddrExprs(AM);
2587 addFullAddress(BuildMI(BB, X86::LEA32r, 4, Result), XAM);
2592 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op1)) {
2594 if (CN->getValue() == 1) { // add X, 1 -> inc X
2595 switch (N.getValueType()) {
2596 default: assert(0 && "Cannot integer add this type!");
2597 case MVT::i8: Opc = X86::INC8r; break;
2598 case MVT::i16: Opc = X86::INC16r; break;
2599 case MVT::i32: Opc = X86::INC32r; break;
2601 } else if (CN->isAllOnesValue()) { // add X, -1 -> dec X
2602 switch (N.getValueType()) {
2603 default: assert(0 && "Cannot integer add this type!");
2604 case MVT::i8: Opc = X86::DEC8r; break;
2605 case MVT::i16: Opc = X86::DEC16r; break;
2606 case MVT::i32: Opc = X86::DEC32r; break;
2611 Tmp1 = SelectExpr(Op0);
2612 BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2616 switch (N.getValueType()) {
2617 default: assert(0 && "Cannot add this type!");
2618 case MVT::i8: Opc = X86::ADD8ri; break;
2619 case MVT::i16: Opc = X86::ADD16ri; break;
2620 case MVT::i32: Opc = X86::ADD32ri; break;
2623 Tmp1 = SelectExpr(Op0);
2624 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
2629 switch (N.getValueType()) {
2630 default: assert(0 && "Cannot add this type!");
2631 case MVT::i8: Opc = X86::ADD8rr; break;
2632 case MVT::i16: Opc = X86::ADD16rr; break;
2633 case MVT::i32: Opc = X86::ADD32rr; break;
2634 case MVT::f32: Opc = X86::ADDSSrr; break;
2635 case MVT::f64: Opc = X86ScalarSSE ? X86::ADDSDrr : X86::FpADD; break;
2638 if (getRegPressure(Op0) > getRegPressure(Op1)) {
2639 Tmp1 = SelectExpr(Op0);
2640 Tmp2 = SelectExpr(Op1);
2642 Tmp2 = SelectExpr(Op1);
2643 Tmp1 = SelectExpr(Op0);
2646 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
2650 Tmp1 = SelectExpr(Node->getOperand(0));
2652 Opc = (N.getValueType() == MVT::f32) ? X86::SQRTSSrr : X86::SQRTSDrr;
2653 BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2655 BuildMI(BB, X86::FSQRT, 1, Result).addReg(Tmp1);
2660 // Once we can spill 16 byte constants into the constant pool, we can
2661 // implement SSE equivalents of FABS and FCHS.
2666 assert(N.getValueType()==MVT::f64 && "Illegal type for this operation");
2667 Tmp1 = SelectExpr(Node->getOperand(0));
2668 switch (N.getOpcode()) {
2669 default: assert(0 && "Unreachable!");
2670 case ISD::FABS: BuildMI(BB, X86::FABS, 1, Result).addReg(Tmp1); break;
2671 case ISD::FNEG: BuildMI(BB, X86::FCHS, 1, Result).addReg(Tmp1); break;
2672 case ISD::FSIN: BuildMI(BB, X86::FSIN, 1, Result).addReg(Tmp1); break;
2673 case ISD::FCOS: BuildMI(BB, X86::FCOS, 1, Result).addReg(Tmp1); break;
2678 switch (N.getValueType()) {
2679 default: assert(0 && "Unsupported VT!");
2680 case MVT::i8: Tmp2 = X86::MUL8r; break;
2681 case MVT::i16: Tmp2 = X86::MUL16r; break;
2682 case MVT::i32: Tmp2 = X86::MUL32r; break;
2686 unsigned MovOpc, LowReg, HiReg;
2687 switch (N.getValueType()) {
2688 default: assert(0 && "Unsupported VT!");
2690 MovOpc = X86::MOV8rr;
2696 MovOpc = X86::MOV16rr;
2702 MovOpc = X86::MOV32rr;
2708 if (Node->getOpcode() != ISD::MULHS)
2709 Opc = Tmp2; // Get the MULHU opcode.
2711 Op0 = Node->getOperand(0);
2712 Op1 = Node->getOperand(1);
2713 if (getRegPressure(Op0) > getRegPressure(Op1)) {
2714 Tmp1 = SelectExpr(Op0);
2715 Tmp2 = SelectExpr(Op1);
2717 Tmp2 = SelectExpr(Op1);
2718 Tmp1 = SelectExpr(Op0);
2721 // FIXME: Implement folding of loads into the memory operands here!
2722 BuildMI(BB, MovOpc, 1, LowReg).addReg(Tmp1);
2723 BuildMI(BB, Opc, 1).addReg(Tmp2);
2724 BuildMI(BB, MovOpc, 1, Result).addReg(HiReg);
2733 static const unsigned SUBTab[] = {
2734 X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, 0,
2735 X86::SUB8rm, X86::SUB16rm, X86::SUB32rm, X86::FSUB32m, X86::FSUB64m,
2736 X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::FpSUB , X86::FpSUB,
2738 static const unsigned SSE_SUBTab[] = {
2739 X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, 0,
2740 X86::SUB8rm, X86::SUB16rm, X86::SUB32rm, X86::SUBSSrm, X86::SUBSDrm,
2741 X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::SUBSSrr, X86::SUBSDrr,
2743 static const unsigned MULTab[] = {
2744 0, X86::IMUL16rri, X86::IMUL32rri, 0, 0,
2745 0, X86::IMUL16rm , X86::IMUL32rm, X86::FMUL32m, X86::FMUL64m,
2746 0, X86::IMUL16rr , X86::IMUL32rr, X86::FpMUL , X86::FpMUL,
2748 static const unsigned SSE_MULTab[] = {
2749 0, X86::IMUL16rri, X86::IMUL32rri, 0, 0,
2750 0, X86::IMUL16rm , X86::IMUL32rm, X86::MULSSrm, X86::MULSDrm,
2751 0, X86::IMUL16rr , X86::IMUL32rr, X86::MULSSrr, X86::MULSDrr,
2753 static const unsigned ANDTab[] = {
2754 X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, 0,
2755 X86::AND8rm, X86::AND16rm, X86::AND32rm, 0, 0,
2756 X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, 0,
2758 static const unsigned ORTab[] = {
2759 X86::OR8ri, X86::OR16ri, X86::OR32ri, 0, 0,
2760 X86::OR8rm, X86::OR16rm, X86::OR32rm, 0, 0,
2761 X86::OR8rr, X86::OR16rr, X86::OR32rr, 0, 0,
2763 static const unsigned XORTab[] = {
2764 X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, 0,
2765 X86::XOR8rm, X86::XOR16rm, X86::XOR32rm, 0, 0,
2766 X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, 0,
2769 Op0 = Node->getOperand(0);
2770 Op1 = Node->getOperand(1);
2772 if (Node->getOpcode() == ISD::OR && Op0.hasOneUse() && Op1.hasOneUse())
2773 if (EmitOrOpOp(Op0, Op1, Result)) // Match SHLD, SHRD, and rotates.
2776 if (Node->getOpcode() == ISD::SUB)
2777 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(0)))
2778 if (CN->isNullValue()) { // 0 - N -> neg N
2779 switch (N.getValueType()) {
2780 default: assert(0 && "Cannot sub this type!");
2782 case MVT::i8: Opc = X86::NEG8r; break;
2783 case MVT::i16: Opc = X86::NEG16r; break;
2784 case MVT::i32: Opc = X86::NEG32r; break;
2786 Tmp1 = SelectExpr(N.getOperand(1));
2787 BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2791 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op1)) {
2792 if (CN->isAllOnesValue() && Node->getOpcode() == ISD::XOR) {
2794 switch (N.getValueType()) {
2795 default: assert(0 && "Cannot add this type!");
2796 case MVT::i1: break; // Not supported, don't invert upper bits!
2797 case MVT::i8: Opc = X86::NOT8r; break;
2798 case MVT::i16: Opc = X86::NOT16r; break;
2799 case MVT::i32: Opc = X86::NOT32r; break;
2802 Tmp1 = SelectExpr(Op0);
2803 BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2808 // Fold common multiplies into LEA instructions.
2809 if (Node->getOpcode() == ISD::MUL && N.getValueType() == MVT::i32) {
2810 switch ((int)CN->getValue()) {
2815 // Remove N from exprmap so SelectAddress doesn't get confused.
2818 SelectAddress(N, AM);
2819 // Restore it to the map.
2820 ExprMap[N] = Result;
2821 addFullAddress(BuildMI(BB, X86::LEA32r, 4, Result), AM);
2826 switch (N.getValueType()) {
2827 default: assert(0 && "Cannot xor this type!");
2829 case MVT::i8: Opc = 0; break;
2830 case MVT::i16: Opc = 1; break;
2831 case MVT::i32: Opc = 2; break;
2833 switch (Node->getOpcode()) {
2834 default: assert(0 && "Unreachable!");
2835 case ISD::SUB: Opc = X86ScalarSSE ? SSE_SUBTab[Opc] : SUBTab[Opc]; break;
2836 case ISD::MUL: Opc = X86ScalarSSE ? SSE_MULTab[Opc] : MULTab[Opc]; break;
2837 case ISD::AND: Opc = ANDTab[Opc]; break;
2838 case ISD::OR: Opc = ORTab[Opc]; break;
2839 case ISD::XOR: Opc = XORTab[Opc]; break;
2841 if (Opc) { // Can't fold MUL:i8 R, imm
2842 Tmp1 = SelectExpr(Op0);
2843 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
2848 if (isFoldableLoad(Op0, Op1, true))
2849 if (Node->getOpcode() != ISD::SUB) {
2850 std::swap(Op0, Op1);
2853 // For FP, emit 'reverse' subract, with a memory operand.
2854 if (N.getValueType() == MVT::f64 && !X86ScalarSSE) {
2855 if (Op0.getOpcode() == ISD::EXTLOAD)
2856 Opc = X86::FSUBR32m;
2858 Opc = X86::FSUBR64m;
2861 EmitFoldedLoad(Op0, AM);
2862 Tmp1 = SelectExpr(Op1);
2863 addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
2868 if (isFoldableLoad(Op1, Op0, true)) {
2870 switch (N.getValueType()) {
2871 default: assert(0 && "Cannot operate on this type!");
2873 case MVT::i8: Opc = 5; break;
2874 case MVT::i16: Opc = 6; break;
2875 case MVT::i32: Opc = 7; break;
2876 case MVT::f32: Opc = 8; break;
2877 // For F64, handle promoted load operations (from F32) as well!
2879 assert((!X86ScalarSSE || Op1.getOpcode() == ISD::LOAD) &&
2880 "SSE load should have been promoted");
2881 Opc = Op1.getOpcode() == ISD::LOAD ? 9 : 8; break;
2883 switch (Node->getOpcode()) {
2884 default: assert(0 && "Unreachable!");
2885 case ISD::SUB: Opc = X86ScalarSSE ? SSE_SUBTab[Opc] : SUBTab[Opc]; break;
2886 case ISD::MUL: Opc = X86ScalarSSE ? SSE_MULTab[Opc] : MULTab[Opc]; break;
2887 case ISD::AND: Opc = ANDTab[Opc]; break;
2888 case ISD::OR: Opc = ORTab[Opc]; break;
2889 case ISD::XOR: Opc = XORTab[Opc]; break;
2893 EmitFoldedLoad(Op1, AM);
2894 Tmp1 = SelectExpr(Op0);
2896 addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
2898 assert(Node->getOpcode() == ISD::MUL &&
2899 N.getValueType() == MVT::i8 && "Unexpected situation!");
2900 // Must use the MUL instruction, which forces use of AL.
2901 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(Tmp1);
2902 addFullAddress(BuildMI(BB, X86::MUL8m, 1), AM);
2903 BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
2908 if (getRegPressure(Op0) > getRegPressure(Op1)) {
2909 Tmp1 = SelectExpr(Op0);
2910 Tmp2 = SelectExpr(Op1);
2912 Tmp2 = SelectExpr(Op1);
2913 Tmp1 = SelectExpr(Op0);
2916 switch (N.getValueType()) {
2917 default: assert(0 && "Cannot add this type!");
2919 case MVT::i8: Opc = 10; break;
2920 case MVT::i16: Opc = 11; break;
2921 case MVT::i32: Opc = 12; break;
2922 case MVT::f32: Opc = 13; break;
2923 case MVT::f64: Opc = 14; break;
2925 switch (Node->getOpcode()) {
2926 default: assert(0 && "Unreachable!");
2927 case ISD::SUB: Opc = X86ScalarSSE ? SSE_SUBTab[Opc] : SUBTab[Opc]; break;
2928 case ISD::MUL: Opc = X86ScalarSSE ? SSE_MULTab[Opc] : MULTab[Opc]; break;
2929 case ISD::AND: Opc = ANDTab[Opc]; break;
2930 case ISD::OR: Opc = ORTab[Opc]; break;
2931 case ISD::XOR: Opc = XORTab[Opc]; break;
2934 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
2936 assert(Node->getOpcode() == ISD::MUL &&
2937 N.getValueType() == MVT::i8 && "Unexpected situation!");
2938 // Must use the MUL instruction, which forces use of AL.
2939 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(Tmp1);
2940 BuildMI(BB, X86::MUL8r, 1).addReg(Tmp2);
2941 BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
2945 case ISD::ADD_PARTS:
2946 case ISD::SUB_PARTS: {
2947 assert(N.getNumOperands() == 4 && N.getValueType() == MVT::i32 &&
2948 "Not an i64 add/sub!");
2949 // Emit all of the operands.
2950 std::vector<unsigned> InVals;
2951 for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)
2952 InVals.push_back(SelectExpr(N.getOperand(i)));
2953 if (N.getOpcode() == ISD::ADD_PARTS) {
2954 BuildMI(BB, X86::ADD32rr, 2, Result).addReg(InVals[0]).addReg(InVals[2]);
2955 BuildMI(BB, X86::ADC32rr,2,Result+1).addReg(InVals[1]).addReg(InVals[3]);
2957 BuildMI(BB, X86::SUB32rr, 2, Result).addReg(InVals[0]).addReg(InVals[2]);
2958 BuildMI(BB, X86::SBB32rr, 2,Result+1).addReg(InVals[1]).addReg(InVals[3]);
2960 return Result+N.ResNo;
2963 case ISD::SHL_PARTS:
2964 case ISD::SRA_PARTS:
2965 case ISD::SRL_PARTS: {
2966 assert(N.getNumOperands() == 3 && N.getValueType() == MVT::i32 &&
2967 "Not an i64 shift!");
2968 unsigned ShiftOpLo = SelectExpr(N.getOperand(0));
2969 unsigned ShiftOpHi = SelectExpr(N.getOperand(1));
2970 unsigned TmpReg = MakeReg(MVT::i32);
2971 if (N.getOpcode() == ISD::SRA_PARTS) {
2972 // If this is a SHR of a Long, then we need to do funny sign extension
2973 // stuff. TmpReg gets the value to use as the high-part if we are
2974 // shifting more than 32 bits.
2975 BuildMI(BB, X86::SAR32ri, 2, TmpReg).addReg(ShiftOpHi).addImm(31);
2977 // Other shifts use a fixed zero value if the shift is more than 32 bits.
2978 BuildMI(BB, X86::MOV32ri, 1, TmpReg).addImm(0);
2981 // Initialize CL with the shift amount.
2982 unsigned ShiftAmountReg = SelectExpr(N.getOperand(2));
2983 BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
2985 unsigned TmpReg2 = MakeReg(MVT::i32);
2986 unsigned TmpReg3 = MakeReg(MVT::i32);
2987 if (N.getOpcode() == ISD::SHL_PARTS) {
2988 // TmpReg2 = shld inHi, inLo
2989 BuildMI(BB, X86::SHLD32rrCL, 2,TmpReg2).addReg(ShiftOpHi)
2991 // TmpReg3 = shl inLo, CL
2992 BuildMI(BB, X86::SHL32rCL, 1, TmpReg3).addReg(ShiftOpLo);
2994 // Set the flags to indicate whether the shift was by more than 32 bits.
2995 BuildMI(BB, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
2997 // DestHi = (>32) ? TmpReg3 : TmpReg2;
2998 BuildMI(BB, X86::CMOVNE32rr, 2,
2999 Result+1).addReg(TmpReg2).addReg(TmpReg3);
3000 // DestLo = (>32) ? TmpReg : TmpReg3;
3001 BuildMI(BB, X86::CMOVNE32rr, 2,
3002 Result).addReg(TmpReg3).addReg(TmpReg);
3004 // TmpReg2 = shrd inLo, inHi
3005 BuildMI(BB, X86::SHRD32rrCL,2,TmpReg2).addReg(ShiftOpLo)
3007 // TmpReg3 = s[ah]r inHi, CL
3008 BuildMI(BB, N.getOpcode() == ISD::SRA_PARTS ? X86::SAR32rCL
3009 : X86::SHR32rCL, 1, TmpReg3)
3012 // Set the flags to indicate whether the shift was by more than 32 bits.
3013 BuildMI(BB, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
3015 // DestLo = (>32) ? TmpReg3 : TmpReg2;
3016 BuildMI(BB, X86::CMOVNE32rr, 2,
3017 Result).addReg(TmpReg2).addReg(TmpReg3);
3019 // DestHi = (>32) ? TmpReg : TmpReg3;
3020 BuildMI(BB, X86::CMOVNE32rr, 2,
3021 Result+1).addReg(TmpReg3).addReg(TmpReg);
3023 return Result+N.ResNo;
3027 EmitSelectCC(N.getOperand(0), N.getOperand(1), N.getOperand(2),
3028 N.getValueType(), Result);
3035 assert((N.getOpcode() != ISD::SREM || MVT::isInteger(N.getValueType())) &&
3036 "We don't support this operator!");
3038 if (N.getOpcode() == ISD::SDIV) {
3039 // We can fold loads into FpDIVs, but not really into any others.
3040 if (N.getValueType() == MVT::f64 && !X86ScalarSSE) {
3041 // Check for reversed and unreversed DIV.
3042 if (isFoldableLoad(N.getOperand(0), N.getOperand(1), true)) {
3043 if (N.getOperand(0).getOpcode() == ISD::EXTLOAD)
3044 Opc = X86::FDIVR32m;
3046 Opc = X86::FDIVR64m;
3048 EmitFoldedLoad(N.getOperand(0), AM);
3049 Tmp1 = SelectExpr(N.getOperand(1));
3050 addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
3052 } else if (isFoldableLoad(N.getOperand(1), N.getOperand(0), true) &&
3053 N.getOperand(1).getOpcode() == ISD::LOAD) {
3054 if (N.getOperand(1).getOpcode() == ISD::EXTLOAD)
3059 EmitFoldedLoad(N.getOperand(1), AM);
3060 Tmp1 = SelectExpr(N.getOperand(0));
3061 addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
3066 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
3067 // FIXME: These special cases should be handled by the lowering impl!
3068 unsigned RHS = CN->getValue();
3074 if (RHS && (RHS & (RHS-1)) == 0) { // Signed division by power of 2?
3075 unsigned Log = Log2_32(RHS);
3076 unsigned SAROpc, SHROpc, ADDOpc, NEGOpc;
3077 switch (N.getValueType()) {
3078 default: assert("Unknown type to signed divide!");
3080 SAROpc = X86::SAR8ri;
3081 SHROpc = X86::SHR8ri;
3082 ADDOpc = X86::ADD8rr;
3083 NEGOpc = X86::NEG8r;
3086 SAROpc = X86::SAR16ri;
3087 SHROpc = X86::SHR16ri;
3088 ADDOpc = X86::ADD16rr;
3089 NEGOpc = X86::NEG16r;
3092 SAROpc = X86::SAR32ri;
3093 SHROpc = X86::SHR32ri;
3094 ADDOpc = X86::ADD32rr;
3095 NEGOpc = X86::NEG32r;
3098 unsigned RegSize = MVT::getSizeInBits(N.getValueType());
3099 Tmp1 = SelectExpr(N.getOperand(0));
3102 TmpReg = MakeReg(N.getValueType());
3103 BuildMI(BB, SAROpc, 2, TmpReg).addReg(Tmp1).addImm(Log-1);
3107 unsigned TmpReg2 = MakeReg(N.getValueType());
3108 BuildMI(BB, SHROpc, 2, TmpReg2).addReg(TmpReg).addImm(RegSize-Log);
3109 unsigned TmpReg3 = MakeReg(N.getValueType());
3110 BuildMI(BB, ADDOpc, 2, TmpReg3).addReg(Tmp1).addReg(TmpReg2);
3112 unsigned TmpReg4 = isNeg ? MakeReg(N.getValueType()) : Result;
3113 BuildMI(BB, SAROpc, 2, TmpReg4).addReg(TmpReg3).addImm(Log);
3115 BuildMI(BB, NEGOpc, 1, Result).addReg(TmpReg4);
3121 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3122 Tmp1 = SelectExpr(N.getOperand(0));
3123 Tmp2 = SelectExpr(N.getOperand(1));
3125 Tmp2 = SelectExpr(N.getOperand(1));
3126 Tmp1 = SelectExpr(N.getOperand(0));
3129 bool isSigned = N.getOpcode() == ISD::SDIV || N.getOpcode() == ISD::SREM;
3130 bool isDiv = N.getOpcode() == ISD::SDIV || N.getOpcode() == ISD::UDIV;
3131 unsigned LoReg, HiReg, DivOpcode, MovOpcode, ClrOpcode, SExtOpcode;
3132 switch (N.getValueType()) {
3133 default: assert(0 && "Cannot sdiv this type!");
3135 DivOpcode = isSigned ? X86::IDIV8r : X86::DIV8r;
3138 MovOpcode = X86::MOV8rr;
3139 ClrOpcode = X86::MOV8ri;
3140 SExtOpcode = X86::CBW;
3143 DivOpcode = isSigned ? X86::IDIV16r : X86::DIV16r;
3146 MovOpcode = X86::MOV16rr;
3147 ClrOpcode = X86::MOV16ri;
3148 SExtOpcode = X86::CWD;
3151 DivOpcode = isSigned ? X86::IDIV32r : X86::DIV32r;
3154 MovOpcode = X86::MOV32rr;
3155 ClrOpcode = X86::MOV32ri;
3156 SExtOpcode = X86::CDQ;
3159 BuildMI(BB, X86::DIVSSrr, 2, Result).addReg(Tmp1).addReg(Tmp2);
3162 Opc = X86ScalarSSE ? X86::DIVSDrr : X86::FpDIV;
3163 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
3167 // Set up the low part.
3168 BuildMI(BB, MovOpcode, 1, LoReg).addReg(Tmp1);
3171 // Sign extend the low part into the high part.
3172 BuildMI(BB, SExtOpcode, 0);
3174 // Zero out the high part, effectively zero extending the input.
3175 BuildMI(BB, ClrOpcode, 1, HiReg).addImm(0);
3178 // Emit the DIV/IDIV instruction.
3179 BuildMI(BB, DivOpcode, 1).addReg(Tmp2);
3181 // Get the result of the divide or rem.
3182 BuildMI(BB, MovOpcode, 1, Result).addReg(isDiv ? LoReg : HiReg);
3187 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
3188 if (CN->getValue() == 1) { // X = SHL Y, 1 -> X = ADD Y, Y
3189 switch (N.getValueType()) {
3190 default: assert(0 && "Cannot shift this type!");
3191 case MVT::i8: Opc = X86::ADD8rr; break;
3192 case MVT::i16: Opc = X86::ADD16rr; break;
3193 case MVT::i32: Opc = X86::ADD32rr; break;
3195 Tmp1 = SelectExpr(N.getOperand(0));
3196 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp1);
3200 switch (N.getValueType()) {
3201 default: assert(0 && "Cannot shift this type!");
3202 case MVT::i8: Opc = X86::SHL8ri; break;
3203 case MVT::i16: Opc = X86::SHL16ri; break;
3204 case MVT::i32: Opc = X86::SHL32ri; break;
3206 Tmp1 = SelectExpr(N.getOperand(0));
3207 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
3211 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3212 Tmp1 = SelectExpr(N.getOperand(0));
3213 Tmp2 = SelectExpr(N.getOperand(1));
3215 Tmp2 = SelectExpr(N.getOperand(1));
3216 Tmp1 = SelectExpr(N.getOperand(0));
3219 switch (N.getValueType()) {
3220 default: assert(0 && "Cannot shift this type!");
3221 case MVT::i8 : Opc = X86::SHL8rCL; break;
3222 case MVT::i16: Opc = X86::SHL16rCL; break;
3223 case MVT::i32: Opc = X86::SHL32rCL; break;
3225 BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(Tmp2);
3226 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
3229 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
3230 switch (N.getValueType()) {
3231 default: assert(0 && "Cannot shift this type!");
3232 case MVT::i8: Opc = X86::SHR8ri; break;
3233 case MVT::i16: Opc = X86::SHR16ri; break;
3234 case MVT::i32: Opc = X86::SHR32ri; break;
3236 Tmp1 = SelectExpr(N.getOperand(0));
3237 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
3241 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3242 Tmp1 = SelectExpr(N.getOperand(0));
3243 Tmp2 = SelectExpr(N.getOperand(1));
3245 Tmp2 = SelectExpr(N.getOperand(1));
3246 Tmp1 = SelectExpr(N.getOperand(0));
3249 switch (N.getValueType()) {
3250 default: assert(0 && "Cannot shift this type!");
3251 case MVT::i8 : Opc = X86::SHR8rCL; break;
3252 case MVT::i16: Opc = X86::SHR16rCL; break;
3253 case MVT::i32: Opc = X86::SHR32rCL; break;
3255 BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(Tmp2);
3256 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
3259 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
3260 switch (N.getValueType()) {
3261 default: assert(0 && "Cannot shift this type!");
3262 case MVT::i8: Opc = X86::SAR8ri; break;
3263 case MVT::i16: Opc = X86::SAR16ri; break;
3264 case MVT::i32: Opc = X86::SAR32ri; break;
3266 Tmp1 = SelectExpr(N.getOperand(0));
3267 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
3271 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3272 Tmp1 = SelectExpr(N.getOperand(0));
3273 Tmp2 = SelectExpr(N.getOperand(1));
3275 Tmp2 = SelectExpr(N.getOperand(1));
3276 Tmp1 = SelectExpr(N.getOperand(0));
3279 switch (N.getValueType()) {
3280 default: assert(0 && "Cannot shift this type!");
3281 case MVT::i8 : Opc = X86::SAR8rCL; break;
3282 case MVT::i16: Opc = X86::SAR16rCL; break;
3283 case MVT::i32: Opc = X86::SAR32rCL; break;
3285 BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(Tmp2);
3286 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
3290 EmitCMP(N.getOperand(0), N.getOperand(1), Node->hasOneUse());
3291 EmitSetCC(BB, Result, cast<CondCodeSDNode>(N.getOperand(2))->get(),
3292 MVT::isFloatingPoint(N.getOperand(1).getValueType()));
3295 // Make sure we generate both values.
3296 if (Result != 1) { // Generate the token
3297 if (!ExprMap.insert(std::make_pair(N.getValue(1), 1)).second)
3298 assert(0 && "Load already emitted!?");
3300 Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
3302 switch (Node->getValueType(0)) {
3303 default: assert(0 && "Cannot load this type!");
3305 case MVT::i8: Opc = X86::MOV8rm; break;
3306 case MVT::i16: Opc = X86::MOV16rm; break;
3307 case MVT::i32: Opc = X86::MOV32rm; break;
3308 case MVT::f32: Opc = X86::MOVSSrm; break;
3314 ContainsFPCode = true;
3319 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N.getOperand(1))){
3320 Select(N.getOperand(0));
3321 addConstantPoolReference(BuildMI(BB, Opc, 4, Result), CP->getIndex());
3325 SDOperand Chain = N.getOperand(0);
3326 SDOperand Address = N.getOperand(1);
3327 if (getRegPressure(Chain) > getRegPressure(Address)) {
3329 SelectAddress(Address, AM);
3331 SelectAddress(Address, AM);
3335 addFullAddress(BuildMI(BB, Opc, 4, Result), AM);
3338 case X86ISD::FILD64m:
3339 // Make sure we generate both values.
3340 assert(Result != 1 && N.getValueType() == MVT::f64);
3341 if (!ExprMap.insert(std::make_pair(N.getValue(1), 1)).second)
3342 assert(0 && "Load already emitted!?");
3347 SDOperand Chain = N.getOperand(0);
3348 SDOperand Address = N.getOperand(1);
3349 if (getRegPressure(Chain) > getRegPressure(Address)) {
3351 SelectAddress(Address, AM);
3353 SelectAddress(Address, AM);
3357 addFullAddress(BuildMI(BB, X86::FILD64m, 4, Result), AM);
3361 case ISD::EXTLOAD: // Arbitrarily codegen extloads as MOVZX*
3362 case ISD::ZEXTLOAD: {
3363 // Make sure we generate both values.
3365 ExprMap[N.getValue(1)] = 1; // Generate the token
3367 Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
3369 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N.getOperand(1)))
3370 if (Node->getValueType(0) == MVT::f64) {
3371 assert(cast<VTSDNode>(Node->getOperand(3))->getVT() == MVT::f32 &&
3373 addConstantPoolReference(BuildMI(BB, X86::FLD32m, 4, Result),
3379 if (getRegPressure(Node->getOperand(0)) >
3380 getRegPressure(Node->getOperand(1))) {
3381 Select(Node->getOperand(0)); // chain
3382 SelectAddress(Node->getOperand(1), AM);
3384 SelectAddress(Node->getOperand(1), AM);
3385 Select(Node->getOperand(0)); // chain
3388 switch (Node->getValueType(0)) {
3389 default: assert(0 && "Unknown type to sign extend to.");
3391 assert(cast<VTSDNode>(Node->getOperand(3))->getVT() == MVT::f32 &&
3393 addFullAddress(BuildMI(BB, X86::FLD32m, 5, Result), AM);
3396 switch (cast<VTSDNode>(Node->getOperand(3))->getVT()) {
3398 assert(0 && "Bad zero extend!");
3401 addFullAddress(BuildMI(BB, X86::MOVZX32rm8, 5, Result), AM);
3404 addFullAddress(BuildMI(BB, X86::MOVZX32rm16, 5, Result), AM);
3409 assert(cast<VTSDNode>(Node->getOperand(3))->getVT() <= MVT::i8 &&
3410 "Bad zero extend!");
3411 addFullAddress(BuildMI(BB, X86::MOVSX16rm8, 5, Result), AM);
3414 assert(cast<VTSDNode>(Node->getOperand(3))->getVT() == MVT::i1 &&
3415 "Bad zero extend!");
3416 addFullAddress(BuildMI(BB, X86::MOV8rm, 5, Result), AM);
3421 case ISD::SEXTLOAD: {
3422 // Make sure we generate both values.
3424 ExprMap[N.getValue(1)] = 1; // Generate the token
3426 Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
3429 if (getRegPressure(Node->getOperand(0)) >
3430 getRegPressure(Node->getOperand(1))) {
3431 Select(Node->getOperand(0)); // chain
3432 SelectAddress(Node->getOperand(1), AM);
3434 SelectAddress(Node->getOperand(1), AM);
3435 Select(Node->getOperand(0)); // chain
3438 switch (Node->getValueType(0)) {
3439 case MVT::i8: assert(0 && "Cannot sign extend from bool!");
3440 default: assert(0 && "Unknown type to sign extend to.");
3442 switch (cast<VTSDNode>(Node->getOperand(3))->getVT()) {
3444 case MVT::i1: assert(0 && "Cannot sign extend from bool!");
3446 addFullAddress(BuildMI(BB, X86::MOVSX32rm8, 5, Result), AM);
3449 addFullAddress(BuildMI(BB, X86::MOVSX32rm16, 5, Result), AM);
3454 assert(cast<VTSDNode>(Node->getOperand(3))->getVT() == MVT::i8 &&
3455 "Cannot sign extend from bool!");
3456 addFullAddress(BuildMI(BB, X86::MOVSX16rm8, 5, Result), AM);
3462 case ISD::DYNAMIC_STACKALLOC:
3463 // Generate both result values.
3465 ExprMap[N.getValue(1)] = 1; // Generate the token
3467 Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
3469 // FIXME: We are currently ignoring the requested alignment for handling
3470 // greater than the stack alignment. This will need to be revisited at some
3471 // point. Align = N.getOperand(2);
3473 if (!isa<ConstantSDNode>(N.getOperand(2)) ||
3474 cast<ConstantSDNode>(N.getOperand(2))->getValue() != 0) {
3475 std::cerr << "Cannot allocate stack object with greater alignment than"
3476 << " the stack alignment yet!";
3480 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
3481 Select(N.getOperand(0));
3482 BuildMI(BB, X86::SUB32ri, 2, X86::ESP).addReg(X86::ESP)
3483 .addImm(CN->getValue());
3485 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3486 Select(N.getOperand(0));
3487 Tmp1 = SelectExpr(N.getOperand(1));
3489 Tmp1 = SelectExpr(N.getOperand(1));
3490 Select(N.getOperand(0));
3493 // Subtract size from stack pointer, thereby allocating some space.
3494 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(Tmp1);
3497 // Put a pointer to the space into the result register, by copying the stack
3499 BuildMI(BB, X86::MOV32rr, 1, Result).addReg(X86::ESP);
3502 case X86ISD::TAILCALL:
3503 case X86ISD::CALL: {
3504 // The chain for this call is now lowered.
3505 ExprMap.insert(std::make_pair(N.getValue(0), 1));
3507 bool isDirect = isa<GlobalAddressSDNode>(N.getOperand(1)) ||
3508 isa<ExternalSymbolSDNode>(N.getOperand(1));
3509 unsigned Callee = 0;
3511 Select(N.getOperand(0));
3513 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3514 Select(N.getOperand(0));
3515 Callee = SelectExpr(N.getOperand(1));
3517 Callee = SelectExpr(N.getOperand(1));
3518 Select(N.getOperand(0));
3522 // If this call has values to pass in registers, do so now.
3523 if (Node->getNumOperands() > 4) {
3524 // The first value is passed in (a part of) EAX, the second in EDX.
3525 unsigned RegOp1 = SelectExpr(N.getOperand(4));
3527 Node->getNumOperands() > 5 ? SelectExpr(N.getOperand(5)) : 0;
3529 switch (N.getOperand(4).getValueType()) {
3530 default: assert(0 && "Bad thing to pass in regs");
3532 case MVT::i8: BuildMI(BB, X86::MOV8rr , 1,X86::AL).addReg(RegOp1); break;
3533 case MVT::i16: BuildMI(BB, X86::MOV16rr, 1,X86::AX).addReg(RegOp1); break;
3534 case MVT::i32: BuildMI(BB, X86::MOV32rr, 1,X86::EAX).addReg(RegOp1);break;
3537 switch (N.getOperand(5).getValueType()) {
3538 default: assert(0 && "Bad thing to pass in regs");
3541 BuildMI(BB, X86::MOV8rr , 1, X86::DL).addReg(RegOp2);
3544 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(RegOp2);
3547 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RegOp2);
3552 if (GlobalAddressSDNode *GASD =
3553 dyn_cast<GlobalAddressSDNode>(N.getOperand(1))) {
3554 BuildMI(BB, X86::CALLpcrel32, 1).addGlobalAddress(GASD->getGlobal(),true);
3555 } else if (ExternalSymbolSDNode *ESSDN =
3556 dyn_cast<ExternalSymbolSDNode>(N.getOperand(1))) {
3557 BuildMI(BB, X86::CALLpcrel32,
3558 1).addExternalSymbol(ESSDN->getSymbol(), true);
3560 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3561 Select(N.getOperand(0));
3562 Tmp1 = SelectExpr(N.getOperand(1));
3564 Tmp1 = SelectExpr(N.getOperand(1));
3565 Select(N.getOperand(0));
3568 BuildMI(BB, X86::CALL32r, 1).addReg(Tmp1);
3571 // Get caller stack amount and amount the callee added to the stack pointer.
3572 Tmp1 = cast<ConstantSDNode>(N.getOperand(2))->getValue();
3573 Tmp2 = cast<ConstantSDNode>(N.getOperand(3))->getValue();
3574 BuildMI(BB, X86::ADJCALLSTACKUP, 2).addImm(Tmp1).addImm(Tmp2);
3576 if (Node->getNumValues() != 1)
3577 switch (Node->getValueType(1)) {
3578 default: assert(0 && "Unknown value type for call result!");
3579 case MVT::Other: return 1;
3582 BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
3585 BuildMI(BB, X86::MOV16rr, 1, Result).addReg(X86::AX);
3588 BuildMI(BB, X86::MOV32rr, 1, Result).addReg(X86::EAX);
3589 if (Node->getNumValues() == 3 && Node->getValueType(2) == MVT::i32)
3590 BuildMI(BB, X86::MOV32rr, 1, Result+1).addReg(X86::EDX);
3592 case MVT::f64: // Floating-point return values live in %ST(0)
3594 ContainsFPCode = true;
3595 BuildMI(BB, X86::FpGETRESULT, 1, X86::FP0);
3597 unsigned Size = MVT::getSizeInBits(MVT::f64)/8;
3598 MachineFunction *F = BB->getParent();
3599 int FrameIdx = F->getFrameInfo()->CreateStackObject(Size, Size);
3600 addFrameReference(BuildMI(BB, X86::FST64m, 5), FrameIdx).addReg(X86::FP0);
3601 addFrameReference(BuildMI(BB, X86::MOVSDrm, 4, Result), FrameIdx);
3604 ContainsFPCode = true;
3605 BuildMI(BB, X86::FpGETRESULT, 1, Result);
3609 return Result+N.ResNo-1;
3612 // First, determine that the size of the operand falls within the acceptable
3613 // range for this architecture.
3615 if (Node->getOperand(1).getValueType() != MVT::i16) {
3616 std::cerr << "llvm.readport: Address size is not 16 bits\n";
3620 // Make sure we generate both values.
3621 if (Result != 1) { // Generate the token
3622 if (!ExprMap.insert(std::make_pair(N.getValue(1), 1)).second)
3623 assert(0 && "readport already emitted!?");
3625 Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
3627 Select(Node->getOperand(0)); // Select the chain.
3629 // If the port is a single-byte constant, use the immediate form.
3630 if (ConstantSDNode *Port = dyn_cast<ConstantSDNode>(Node->getOperand(1)))
3631 if ((Port->getValue() & 255) == Port->getValue()) {
3632 switch (Node->getValueType(0)) {
3634 BuildMI(BB, X86::IN8ri, 1).addImm(Port->getValue());
3635 BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
3638 BuildMI(BB, X86::IN16ri, 1).addImm(Port->getValue());
3639 BuildMI(BB, X86::MOV16rr, 1, Result).addReg(X86::AX);
3642 BuildMI(BB, X86::IN32ri, 1).addImm(Port->getValue());
3643 BuildMI(BB, X86::MOV32rr, 1, Result).addReg(X86::EAX);
3649 // Now, move the I/O port address into the DX register and use the IN
3650 // instruction to get the input data.
3652 Tmp1 = SelectExpr(Node->getOperand(1));
3653 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Tmp1);
3654 switch (Node->getValueType(0)) {
3656 BuildMI(BB, X86::IN8rr, 0);
3657 BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
3660 BuildMI(BB, X86::IN16rr, 0);
3661 BuildMI(BB, X86::MOV16rr, 1, Result).addReg(X86::AX);
3664 BuildMI(BB, X86::IN32rr, 0);
3665 BuildMI(BB, X86::MOV32rr, 1, Result).addReg(X86::EAX);
3668 std::cerr << "Cannot do input on this data type";
3677 /// TryToFoldLoadOpStore - Given a store node, try to fold together a
3678 /// load/op/store instruction. If successful return true.
3679 bool ISel::TryToFoldLoadOpStore(SDNode *Node) {
3680 assert(Node->getOpcode() == ISD::STORE && "Can only do this for stores!");
3681 SDOperand Chain = Node->getOperand(0);
3682 SDOperand StVal = Node->getOperand(1);
3683 SDOperand StPtr = Node->getOperand(2);
3685 // The chain has to be a load, the stored value must be an integer binary
3686 // operation with one use.
3687 if (!StVal.Val->hasOneUse() || StVal.Val->getNumOperands() != 2 ||
3688 MVT::isFloatingPoint(StVal.getValueType()))
3691 // Token chain must either be a factor node or the load to fold.
3692 if (Chain.getOpcode() != ISD::LOAD && Chain.getOpcode() != ISD::TokenFactor)
3697 // Check to see if there is a load from the same pointer that we're storing
3698 // to in either operand of the binop.
3699 if (StVal.getOperand(0).getOpcode() == ISD::LOAD &&
3700 StVal.getOperand(0).getOperand(1) == StPtr)
3701 TheLoad = StVal.getOperand(0);
3702 else if (StVal.getOperand(1).getOpcode() == ISD::LOAD &&
3703 StVal.getOperand(1).getOperand(1) == StPtr)
3704 TheLoad = StVal.getOperand(1);
3706 return false; // No matching load operand.
3708 // We can only fold the load if there are no intervening side-effecting
3709 // operations. This means that the store uses the load as its token chain, or
3710 // there are only token factor nodes in between the store and load.
3711 if (Chain != TheLoad.getValue(1)) {
3712 // Okay, the other option is that we have a store referring to (possibly
3713 // nested) token factor nodes. For now, just try peeking through one level
3714 // of token factors to see if this is the case.
3715 bool ChainOk = false;
3716 if (Chain.getOpcode() == ISD::TokenFactor) {
3717 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
3718 if (Chain.getOperand(i) == TheLoad.getValue(1)) {
3724 if (!ChainOk) return false;
3727 if (TheLoad.getOperand(1) != StPtr)
3730 // Make sure that one of the operands of the binop is the load, and that the
3731 // load folds into the binop.
3732 if (((StVal.getOperand(0) != TheLoad ||
3733 !isFoldableLoad(TheLoad, StVal.getOperand(1))) &&
3734 (StVal.getOperand(1) != TheLoad ||
3735 !isFoldableLoad(TheLoad, StVal.getOperand(0)))))
3738 // Finally, check to see if this is one of the ops we can handle!
3739 static const unsigned ADDTAB[] = {
3740 X86::ADD8mi, X86::ADD16mi, X86::ADD32mi,
3741 X86::ADD8mr, X86::ADD16mr, X86::ADD32mr,
3743 static const unsigned SUBTAB[] = {
3744 X86::SUB8mi, X86::SUB16mi, X86::SUB32mi,
3745 X86::SUB8mr, X86::SUB16mr, X86::SUB32mr,
3747 static const unsigned ANDTAB[] = {
3748 X86::AND8mi, X86::AND16mi, X86::AND32mi,
3749 X86::AND8mr, X86::AND16mr, X86::AND32mr,
3751 static const unsigned ORTAB[] = {
3752 X86::OR8mi, X86::OR16mi, X86::OR32mi,
3753 X86::OR8mr, X86::OR16mr, X86::OR32mr,
3755 static const unsigned XORTAB[] = {
3756 X86::XOR8mi, X86::XOR16mi, X86::XOR32mi,
3757 X86::XOR8mr, X86::XOR16mr, X86::XOR32mr,
3759 static const unsigned SHLTAB[] = {
3760 X86::SHL8mi, X86::SHL16mi, X86::SHL32mi,
3761 /*Have to put the reg in CL*/0, 0, 0,
3763 static const unsigned SARTAB[] = {
3764 X86::SAR8mi, X86::SAR16mi, X86::SAR32mi,
3765 /*Have to put the reg in CL*/0, 0, 0,
3767 static const unsigned SHRTAB[] = {
3768 X86::SHR8mi, X86::SHR16mi, X86::SHR32mi,
3769 /*Have to put the reg in CL*/0, 0, 0,
3772 const unsigned *TabPtr = 0;
3773 switch (StVal.getOpcode()) {
3775 std::cerr << "CANNOT [mem] op= val: ";
3776 StVal.Val->dump(); std::cerr << "\n";
3781 case ISD::UREM: return false;
3783 case ISD::ADD: TabPtr = ADDTAB; break;
3784 case ISD::SUB: TabPtr = SUBTAB; break;
3785 case ISD::AND: TabPtr = ANDTAB; break;
3786 case ISD:: OR: TabPtr = ORTAB; break;
3787 case ISD::XOR: TabPtr = XORTAB; break;
3788 case ISD::SHL: TabPtr = SHLTAB; break;
3789 case ISD::SRA: TabPtr = SARTAB; break;
3790 case ISD::SRL: TabPtr = SHRTAB; break;
3793 // Handle: [mem] op= CST
3794 SDOperand Op0 = StVal.getOperand(0);
3795 SDOperand Op1 = StVal.getOperand(1);
3797 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op1)) {
3798 switch (Op0.getValueType()) { // Use Op0's type because of shifts.
3801 case MVT::i8: Opc = TabPtr[0]; break;
3802 case MVT::i16: Opc = TabPtr[1]; break;
3803 case MVT::i32: Opc = TabPtr[2]; break;
3807 if (!ExprMap.insert(std::make_pair(TheLoad.getValue(1), 1)).second)
3808 assert(0 && "Already emitted?");
3812 if (getRegPressure(TheLoad.getOperand(0)) >
3813 getRegPressure(TheLoad.getOperand(1))) {
3814 Select(TheLoad.getOperand(0));
3815 SelectAddress(TheLoad.getOperand(1), AM);
3817 SelectAddress(TheLoad.getOperand(1), AM);
3818 Select(TheLoad.getOperand(0));
3821 if (StVal.getOpcode() == ISD::ADD) {
3822 if (CN->getValue() == 1) {
3823 switch (Op0.getValueType()) {
3826 addFullAddress(BuildMI(BB, X86::INC8m, 4), AM);
3828 case MVT::i16: Opc = TabPtr[1];
3829 addFullAddress(BuildMI(BB, X86::INC16m, 4), AM);
3831 case MVT::i32: Opc = TabPtr[2];
3832 addFullAddress(BuildMI(BB, X86::INC32m, 4), AM);
3835 } else if (CN->getValue()+1 == 0) { // [X] += -1 -> DEC [X]
3836 switch (Op0.getValueType()) {
3839 addFullAddress(BuildMI(BB, X86::DEC8m, 4), AM);
3841 case MVT::i16: Opc = TabPtr[1];
3842 addFullAddress(BuildMI(BB, X86::DEC16m, 4), AM);
3844 case MVT::i32: Opc = TabPtr[2];
3845 addFullAddress(BuildMI(BB, X86::DEC32m, 4), AM);
3851 addFullAddress(BuildMI(BB, Opc, 4+1),AM).addImm(CN->getValue());
3856 // If we have [mem] = V op [mem], try to turn it into:
3857 // [mem] = [mem] op V.
3858 if (Op1 == TheLoad && StVal.getOpcode() != ISD::SUB &&
3859 StVal.getOpcode() != ISD::SHL && StVal.getOpcode() != ISD::SRA &&
3860 StVal.getOpcode() != ISD::SRL)
3861 std::swap(Op0, Op1);
3863 if (Op0 != TheLoad) return false;
3865 switch (Op0.getValueType()) {
3866 default: return false;
3868 case MVT::i8: Opc = TabPtr[3]; break;
3869 case MVT::i16: Opc = TabPtr[4]; break;
3870 case MVT::i32: Opc = TabPtr[5]; break;
3873 // Table entry doesn't exist?
3874 if (Opc == 0) return false;
3876 if (!ExprMap.insert(std::make_pair(TheLoad.getValue(1), 1)).second)
3877 assert(0 && "Already emitted?");
3879 Select(TheLoad.getOperand(0));
3882 SelectAddress(TheLoad.getOperand(1), AM);
3883 unsigned Reg = SelectExpr(Op1);
3884 addFullAddress(BuildMI(BB, Opc, 4+1), AM).addReg(Reg);
3888 /// If node is a ret(tailcall) node, emit the specified tail call and return
3889 /// true, otherwise return false.
3891 /// FIXME: This whole thing should be a post-legalize optimization pass which
3892 /// recognizes and transforms the dag. We don't want the selection phase doing
3895 bool ISel::EmitPotentialTailCall(SDNode *RetNode) {
3896 assert(RetNode->getOpcode() == ISD::RET && "Not a return");
3898 SDOperand Chain = RetNode->getOperand(0);
3900 // If this is a token factor node where one operand is a call, dig into it.
3901 SDOperand TokFactor;
3902 unsigned TokFactorOperand = 0;
3903 if (Chain.getOpcode() == ISD::TokenFactor) {
3904 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
3905 if (Chain.getOperand(i).getOpcode() == ISD::CALLSEQ_END ||
3906 Chain.getOperand(i).getOpcode() == X86ISD::TAILCALL) {
3907 TokFactorOperand = i;
3909 Chain = Chain.getOperand(i);
3912 if (TokFactor.Val == 0) return false; // No call operand.
3915 // Skip the CALLSEQ_END node if present.
3916 if (Chain.getOpcode() == ISD::CALLSEQ_END)
3917 Chain = Chain.getOperand(0);
3919 // Is a tailcall the last control operation that occurs before the return?
3920 if (Chain.getOpcode() != X86ISD::TAILCALL)
3923 // If we return a value, is it the value produced by the call?
3924 if (RetNode->getNumOperands() > 1) {
3925 // Not returning the ret val of the call?
3926 if (Chain.Val->getNumValues() == 1 ||
3927 RetNode->getOperand(1) != Chain.getValue(1))
3930 if (RetNode->getNumOperands() > 2) {
3931 if (Chain.Val->getNumValues() == 2 ||
3932 RetNode->getOperand(2) != Chain.getValue(2))
3935 assert(RetNode->getNumOperands() <= 3);
3938 // CalleeCallArgAmt - The total number of bytes used for the callee arg area.
3939 // For FastCC, this will always be > 0.
3940 unsigned CalleeCallArgAmt =
3941 cast<ConstantSDNode>(Chain.getOperand(2))->getValue();
3943 // CalleeCallArgPopAmt - The number of bytes in the call area popped by the
3944 // callee. For FastCC this will always be > 0, for CCC this is always 0.
3945 unsigned CalleeCallArgPopAmt =
3946 cast<ConstantSDNode>(Chain.getOperand(3))->getValue();
3948 // There are several cases we can handle here. First, if the caller and
3949 // callee are both CCC functions, we can tailcall if the callee takes <= the
3950 // number of argument bytes that the caller does.
3951 if (CalleeCallArgPopAmt == 0 && // Callee is C CallingConv?
3952 X86Lowering.getBytesToPopOnReturn() == 0) { // Caller is C CallingConv?
3953 // Check to see if caller arg area size >= callee arg area size.
3954 if (X86Lowering.getBytesCallerReserves() >= CalleeCallArgAmt) {
3955 //std::cerr << "CCC TAILCALL UNIMP!\n";
3956 // If TokFactor is non-null, emit all operands.
3958 //EmitCCCToCCCTailCall(Chain.Val);
3964 // Second, if both are FastCC functions, we can always perform the tail call.
3965 if (CalleeCallArgPopAmt && X86Lowering.getBytesToPopOnReturn()) {
3966 // If TokFactor is non-null, emit all operands before the call.
3967 if (TokFactor.Val) {
3968 for (unsigned i = 0, e = TokFactor.getNumOperands(); i != e; ++i)
3969 if (i != TokFactorOperand)
3970 Select(TokFactor.getOperand(i));
3973 EmitFastCCToFastCCTailCall(Chain.Val);
3977 // We don't support mixed calls, due to issues with alignment. We could in
3978 // theory handle some mixed calls from CCC -> FastCC if the stack is properly
3979 // aligned (which depends on the number of arguments to the callee). TODO.
3983 static SDOperand GetAdjustedArgumentStores(SDOperand Chain, int Offset,
3984 SelectionDAG &DAG) {
3985 MVT::ValueType StoreVT;
3986 switch (Chain.getOpcode()) {
3987 case ISD::CALLSEQ_START:
3988 // If we found the start of the call sequence, we're done. We actually
3989 // strip off the CALLSEQ_START node, to avoid generating the
3990 // ADJCALLSTACKDOWN marker for the tail call.
3991 return Chain.getOperand(0);
3992 case ISD::TokenFactor: {
3993 std::vector<SDOperand> Ops;
3994 Ops.reserve(Chain.getNumOperands());
3995 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
3996 Ops.push_back(GetAdjustedArgumentStores(Chain.getOperand(i), Offset,DAG));
3997 return DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
3999 case ISD::STORE: // Normal store
4000 StoreVT = Chain.getOperand(1).getValueType();
4002 case ISD::TRUNCSTORE: // FLOAT store
4003 StoreVT = cast<VTSDNode>(Chain.getOperand(4))->getVT();
4007 SDOperand OrigDest = Chain.getOperand(2);
4008 unsigned OrigOffset;
4010 if (OrigDest.getOpcode() == ISD::CopyFromReg) {
4012 assert(cast<RegisterSDNode>(OrigDest.getOperand(1))->getReg() == X86::ESP);
4014 // We expect only (ESP+C)
4015 assert(OrigDest.getOpcode() == ISD::ADD &&
4016 isa<ConstantSDNode>(OrigDest.getOperand(1)) &&
4017 OrigDest.getOperand(0).getOpcode() == ISD::CopyFromReg &&
4018 cast<RegisterSDNode>(OrigDest.getOperand(0).getOperand(1))->getReg()
4020 OrigOffset = cast<ConstantSDNode>(OrigDest.getOperand(1))->getValue();
4023 // Compute the new offset from the incoming ESP value we wish to use.
4024 unsigned NewOffset = OrigOffset + Offset;
4026 unsigned OpSize = (MVT::getSizeInBits(StoreVT)+7)/8; // Bits -> Bytes
4027 MachineFunction &MF = DAG.getMachineFunction();
4028 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, NewOffset);
4029 SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
4031 SDOperand InChain = GetAdjustedArgumentStores(Chain.getOperand(0), Offset,
4033 if (Chain.getOpcode() == ISD::STORE)
4034 return DAG.getNode(ISD::STORE, MVT::Other, InChain, Chain.getOperand(1),
4036 assert(Chain.getOpcode() == ISD::TRUNCSTORE);
4037 return DAG.getNode(ISD::TRUNCSTORE, MVT::Other, InChain, Chain.getOperand(1),
4038 FIN, DAG.getSrcValue(NULL), DAG.getValueType(StoreVT));
4042 /// EmitFastCCToFastCCTailCall - Given a tailcall in the tail position to a
4043 /// fastcc function from a fastcc function, emit the code to emit a 'proper'
4045 void ISel::EmitFastCCToFastCCTailCall(SDNode *TailCallNode) {
4046 unsigned CalleeCallArgSize =
4047 cast<ConstantSDNode>(TailCallNode->getOperand(2))->getValue();
4048 unsigned CallerArgSize = X86Lowering.getBytesToPopOnReturn();
4050 //std::cerr << "****\n*** EMITTING TAIL CALL!\n****\n";
4052 // Adjust argument stores. Instead of storing to [ESP], f.e., store to frame
4053 // indexes that are relative to the incoming ESP. If the incoming and
4054 // outgoing arg sizes are the same we will store to [InESP] instead of
4055 // [CurESP] and the ESP referenced will be relative to the incoming function
4057 int ESPOffset = CallerArgSize-CalleeCallArgSize;
4058 SDOperand AdjustedArgStores =
4059 GetAdjustedArgumentStores(TailCallNode->getOperand(0), ESPOffset, *TheDAG);
4061 // Copy the return address of the caller into a virtual register so we don't
4065 SDOperand RetValAddr = X86Lowering.getReturnAddressFrameIndex(*TheDAG);
4066 RetVal = TheDAG->getLoad(MVT::i32, TheDAG->getEntryNode(),
4067 RetValAddr, TheDAG->getSrcValue(NULL));
4071 // Codegen all of the argument stores.
4072 Select(AdjustedArgStores);
4075 // Emit a store of the saved ret value to the new location.
4076 MachineFunction &MF = TheDAG->getMachineFunction();
4077 int ReturnAddrFI = MF.getFrameInfo()->CreateFixedObject(4, ESPOffset-4);
4078 SDOperand RetValAddr = TheDAG->getFrameIndex(ReturnAddrFI, MVT::i32);
4079 Select(TheDAG->getNode(ISD::STORE, MVT::Other, TheDAG->getEntryNode(),
4080 RetVal, RetValAddr));
4083 // Get the destination value.
4084 SDOperand Callee = TailCallNode->getOperand(1);
4085 bool isDirect = isa<GlobalAddressSDNode>(Callee) ||
4086 isa<ExternalSymbolSDNode>(Callee);
4087 unsigned CalleeReg = 0;
4088 if (!isDirect) CalleeReg = SelectExpr(Callee);
4090 unsigned RegOp1 = 0;
4091 unsigned RegOp2 = 0;
4093 if (TailCallNode->getNumOperands() > 4) {
4094 // The first value is passed in (a part of) EAX, the second in EDX.
4095 RegOp1 = SelectExpr(TailCallNode->getOperand(4));
4096 if (TailCallNode->getNumOperands() > 5)
4097 RegOp2 = SelectExpr(TailCallNode->getOperand(5));
4099 switch (TailCallNode->getOperand(4).getValueType()) {
4100 default: assert(0 && "Bad thing to pass in regs");
4103 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(RegOp1);
4107 BuildMI(BB, X86::MOV16rr, 1,X86::AX).addReg(RegOp1);
4111 BuildMI(BB, X86::MOV32rr, 1,X86::EAX).addReg(RegOp1);
4116 switch (TailCallNode->getOperand(5).getValueType()) {
4117 default: assert(0 && "Bad thing to pass in regs");
4120 BuildMI(BB, X86::MOV8rr, 1, X86::DL).addReg(RegOp2);
4124 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(RegOp2);
4128 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RegOp2);
4136 BuildMI(BB, X86::ADJSTACKPTRri, 2,
4137 X86::ESP).addReg(X86::ESP).addImm(ESPOffset);
4139 // TODO: handle jmp [mem]
4141 BuildMI(BB, X86::TAILJMPr, 1).addReg(CalleeReg);
4142 } else if (GlobalAddressSDNode *GASD = dyn_cast<GlobalAddressSDNode>(Callee)){
4143 BuildMI(BB, X86::TAILJMPd, 1).addGlobalAddress(GASD->getGlobal(), true);
4145 ExternalSymbolSDNode *ESSDN = cast<ExternalSymbolSDNode>(Callee);
4146 BuildMI(BB, X86::TAILJMPd, 1).addExternalSymbol(ESSDN->getSymbol(), true);
4148 // ADD IMPLICIT USE RegOp1/RegOp2's
4152 void ISel::Select(SDOperand N) {
4153 unsigned Tmp1, Tmp2, Opc;
4155 if (!ExprMap.insert(std::make_pair(N, 1)).second)
4156 return; // Already selected.
4158 SDNode *Node = N.Val;
4160 switch (Node->getOpcode()) {
4162 Node->dump(); std::cerr << "\n";
4163 assert(0 && "Node not handled yet!");
4164 case ISD::EntryToken: return; // Noop
4165 case ISD::TokenFactor:
4166 if (Node->getNumOperands() == 2) {
4168 getRegPressure(Node->getOperand(1))>getRegPressure(Node->getOperand(0));
4169 Select(Node->getOperand(OneFirst));
4170 Select(Node->getOperand(!OneFirst));
4172 std::vector<std::pair<unsigned, unsigned> > OpsP;
4173 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
4174 OpsP.push_back(std::make_pair(getRegPressure(Node->getOperand(i)), i));
4175 std::sort(OpsP.begin(), OpsP.end());
4176 std::reverse(OpsP.begin(), OpsP.end());
4177 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
4178 Select(Node->getOperand(OpsP[i].second));
4181 case ISD::CopyToReg:
4182 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(2))) {
4183 Select(N.getOperand(0));
4184 Tmp1 = SelectExpr(N.getOperand(2));
4186 Tmp1 = SelectExpr(N.getOperand(2));
4187 Select(N.getOperand(0));
4189 Tmp2 = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4192 switch (N.getOperand(2).getValueType()) {
4193 default: assert(0 && "Invalid type for operation!");
4195 case MVT::i8: Opc = X86::MOV8rr; break;
4196 case MVT::i16: Opc = X86::MOV16rr; break;
4197 case MVT::i32: Opc = X86::MOV32rr; break;
4198 case MVT::f32: Opc = X86::MOVAPSrr; break;
4201 Opc = X86::MOVAPDrr;
4204 ContainsFPCode = true;
4208 BuildMI(BB, Opc, 1, Tmp2).addReg(Tmp1);
4212 if (N.getOperand(0).getOpcode() == ISD::CALLSEQ_END ||
4213 N.getOperand(0).getOpcode() == X86ISD::TAILCALL ||
4214 N.getOperand(0).getOpcode() == ISD::TokenFactor)
4215 if (EmitPotentialTailCall(Node))
4218 switch (N.getNumOperands()) {
4220 assert(0 && "Unknown return instruction!");
4222 assert(N.getOperand(1).getValueType() == MVT::i32 &&
4223 N.getOperand(2).getValueType() == MVT::i32 &&
4224 "Unknown two-register value!");
4225 if (getRegPressure(N.getOperand(1)) > getRegPressure(N.getOperand(2))) {
4226 Tmp1 = SelectExpr(N.getOperand(1));
4227 Tmp2 = SelectExpr(N.getOperand(2));
4229 Tmp2 = SelectExpr(N.getOperand(2));
4230 Tmp1 = SelectExpr(N.getOperand(1));
4232 Select(N.getOperand(0));
4234 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Tmp1);
4235 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(Tmp2);
4238 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
4239 Select(N.getOperand(0));
4240 Tmp1 = SelectExpr(N.getOperand(1));
4242 Tmp1 = SelectExpr(N.getOperand(1));
4243 Select(N.getOperand(0));
4245 switch (N.getOperand(1).getValueType()) {
4246 default: assert(0 && "All other types should have been promoted!!");
4249 // Spill the value to memory and reload it into top of stack.
4250 unsigned Size = MVT::getSizeInBits(MVT::f32)/8;
4251 MachineFunction *F = BB->getParent();
4252 int FrameIdx = F->getFrameInfo()->CreateStackObject(Size, Size);
4253 addFrameReference(BuildMI(BB, X86::MOVSSmr, 5), FrameIdx).addReg(Tmp1);
4254 addFrameReference(BuildMI(BB, X86::FLD32m, 4, X86::FP0), FrameIdx);
4255 BuildMI(BB, X86::FpSETRESULT, 1).addReg(X86::FP0);
4256 ContainsFPCode = true;
4258 assert(0 && "MVT::f32 only legal with scalar sse fp");
4264 // Spill the value to memory and reload it into top of stack.
4265 unsigned Size = MVT::getSizeInBits(MVT::f64)/8;
4266 MachineFunction *F = BB->getParent();
4267 int FrameIdx = F->getFrameInfo()->CreateStackObject(Size, Size);
4268 addFrameReference(BuildMI(BB, X86::MOVSDmr, 5), FrameIdx).addReg(Tmp1);
4269 addFrameReference(BuildMI(BB, X86::FLD64m, 4, X86::FP0), FrameIdx);
4270 BuildMI(BB, X86::FpSETRESULT, 1).addReg(X86::FP0);
4271 ContainsFPCode = true;
4273 BuildMI(BB, X86::FpSETRESULT, 1).addReg(Tmp1);
4277 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Tmp1);
4282 Select(N.getOperand(0));
4285 if (X86Lowering.getBytesToPopOnReturn() == 0)
4286 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
4288 BuildMI(BB, X86::RETI, 1).addImm(X86Lowering.getBytesToPopOnReturn());
4291 Select(N.getOperand(0));
4292 MachineBasicBlock *Dest =
4293 cast<BasicBlockSDNode>(N.getOperand(1))->getBasicBlock();
4294 BuildMI(BB, X86::JMP, 1).addMBB(Dest);
4299 MachineBasicBlock *Dest =
4300 cast<BasicBlockSDNode>(N.getOperand(2))->getBasicBlock();
4302 // Try to fold a setcc into the branch. If this fails, emit a test/jne
4304 if (EmitBranchCC(Dest, N.getOperand(0), N.getOperand(1))) {
4305 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
4306 Select(N.getOperand(0));
4307 Tmp1 = SelectExpr(N.getOperand(1));
4309 Tmp1 = SelectExpr(N.getOperand(1));
4310 Select(N.getOperand(0));
4312 BuildMI(BB, X86::TEST8rr, 2).addReg(Tmp1).addReg(Tmp1);
4313 BuildMI(BB, X86::JNE, 1).addMBB(Dest);
4320 // If this load could be folded into the only using instruction, and if it
4321 // is safe to emit the instruction here, try to do so now.
4322 if (Node->hasNUsesOfValue(1, 0)) {
4323 SDOperand TheVal = N.getValue(0);
4325 for (SDNode::use_iterator UI = Node->use_begin(); ; ++UI) {
4326 assert(UI != Node->use_end() && "Didn't find use!");
4328 for (unsigned i = 0, e = UN->getNumOperands(); i != e; ++i)
4329 if (UN->getOperand(i) == TheVal) {
4335 // Only handle unary operators right now.
4336 if (User->getNumOperands() == 1) {
4338 SelectExpr(SDOperand(User, 0));
4349 case ISD::DYNAMIC_STACKALLOC:
4350 case X86ISD::TAILCALL:
4355 case ISD::CopyFromReg:
4356 case X86ISD::FILD64m:
4358 SelectExpr(N.getValue(0));
4361 case X86ISD::FP_TO_INT16_IN_MEM:
4362 case X86ISD::FP_TO_INT32_IN_MEM:
4363 case X86ISD::FP_TO_INT64_IN_MEM: {
4364 assert(N.getOperand(1).getValueType() == MVT::f64);
4366 Select(N.getOperand(0)); // Select the token chain
4369 if (getRegPressure(N.getOperand(1)) > getRegPressure(N.getOperand(2))) {
4370 ValReg = SelectExpr(N.getOperand(1));
4371 SelectAddress(N.getOperand(2), AM);
4373 SelectAddress(N.getOperand(2), AM);
4374 ValReg = SelectExpr(N.getOperand(1));
4377 // Change the floating point control register to use "round towards zero"
4378 // mode when truncating to an integer value.
4380 MachineFunction *F = BB->getParent();
4381 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
4382 addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
4384 // Load the old value of the high byte of the control word...
4385 unsigned OldCW = MakeReg(MVT::i16);
4386 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, OldCW), CWFrameIdx);
4388 // Set the high part to be round to zero...
4389 addFrameReference(BuildMI(BB, X86::MOV16mi, 5), CWFrameIdx).addImm(0xC7F);
4391 // Reload the modified control word now...
4392 addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
4394 // Restore the memory image of control word to original value
4395 addFrameReference(BuildMI(BB, X86::MOV16mr, 5), CWFrameIdx).addReg(OldCW);
4397 // Get the X86 opcode to use.
4398 switch (N.getOpcode()) {
4399 case X86ISD::FP_TO_INT16_IN_MEM: Tmp1 = X86::FIST16m; break;
4400 case X86ISD::FP_TO_INT32_IN_MEM: Tmp1 = X86::FIST32m; break;
4401 case X86ISD::FP_TO_INT64_IN_MEM: Tmp1 = X86::FISTP64m; break;
4404 addFullAddress(BuildMI(BB, Tmp1, 5), AM).addReg(ValReg);
4406 // Reload the original control word now.
4407 addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
4411 case ISD::TRUNCSTORE: { // truncstore chain, val, ptr, SRCVALUE, storety
4413 MVT::ValueType StoredTy = cast<VTSDNode>(N.getOperand(4))->getVT();
4414 assert((StoredTy == MVT::i1 || StoredTy == MVT::f32 ||
4415 StoredTy == MVT::i16 /*FIXME: THIS IS JUST FOR TESTING!*/)
4416 && "Unsupported TRUNCSTORE for this target!");
4418 if (StoredTy == MVT::i16) {
4419 // FIXME: This is here just to allow testing. X86 doesn't really have a
4420 // TRUNCSTORE i16 operation, but this is required for targets that do not
4421 // have 16-bit integer registers. We occasionally disable 16-bit integer
4422 // registers to test the promotion code.
4423 Select(N.getOperand(0));
4424 Tmp1 = SelectExpr(N.getOperand(1));
4425 SelectAddress(N.getOperand(2), AM);
4427 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Tmp1);
4428 addFullAddress(BuildMI(BB, X86::MOV16mr, 5), AM).addReg(X86::AX);
4432 // Store of constant bool?
4433 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
4434 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(2))) {
4435 Select(N.getOperand(0));
4436 SelectAddress(N.getOperand(2), AM);
4438 SelectAddress(N.getOperand(2), AM);
4439 Select(N.getOperand(0));
4441 addFullAddress(BuildMI(BB, X86::MOV8mi, 5), AM).addImm(CN->getValue());
4446 default: assert(0 && "Cannot truncstore this type!");
4447 case MVT::i1: Opc = X86::MOV8mr; break;
4449 assert(!X86ScalarSSE && "Cannot truncstore scalar SSE regs");
4450 Opc = X86::FST32m; break;
4453 std::vector<std::pair<unsigned, unsigned> > RP;
4454 RP.push_back(std::make_pair(getRegPressure(N.getOperand(0)), 0));
4455 RP.push_back(std::make_pair(getRegPressure(N.getOperand(1)), 1));
4456 RP.push_back(std::make_pair(getRegPressure(N.getOperand(2)), 2));
4457 std::sort(RP.begin(), RP.end());
4459 Tmp1 = 0; // Silence a warning.
4460 for (unsigned i = 0; i != 3; ++i)
4461 switch (RP[2-i].second) {
4462 default: assert(0 && "Unknown operand number!");
4463 case 0: Select(N.getOperand(0)); break;
4464 case 1: Tmp1 = SelectExpr(N.getOperand(1)); break;
4465 case 2: SelectAddress(N.getOperand(2), AM); break;
4468 addFullAddress(BuildMI(BB, Opc, 4+1), AM).addReg(Tmp1);
4474 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
4476 switch (CN->getValueType(0)) {
4477 default: assert(0 && "Invalid type for operation!");
4479 case MVT::i8: Opc = X86::MOV8mi; break;
4480 case MVT::i16: Opc = X86::MOV16mi; break;
4481 case MVT::i32: Opc = X86::MOV32mi; break;
4484 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(2))) {
4485 Select(N.getOperand(0));
4486 SelectAddress(N.getOperand(2), AM);
4488 SelectAddress(N.getOperand(2), AM);
4489 Select(N.getOperand(0));
4491 addFullAddress(BuildMI(BB, Opc, 4+1), AM).addImm(CN->getValue());
4494 } else if (GlobalAddressSDNode *GA =
4495 dyn_cast<GlobalAddressSDNode>(N.getOperand(1))) {
4496 assert(GA->getValueType(0) == MVT::i32 && "Bad pointer operand");
4498 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(2))) {
4499 Select(N.getOperand(0));
4500 SelectAddress(N.getOperand(2), AM);
4502 SelectAddress(N.getOperand(2), AM);
4503 Select(N.getOperand(0));
4505 GlobalValue *GV = GA->getGlobal();
4506 // For Darwin, external and weak symbols are indirect, so we want to load
4507 // the value at address GV, not the value of GV itself.
4508 if (Subtarget->getIndirectExternAndWeakGlobals() &&
4509 (GV->hasWeakLinkage() || GV->isExternal())) {
4510 Tmp1 = MakeReg(MVT::i32);
4511 BuildMI(BB, X86::MOV32rm, 4, Tmp1).addReg(0).addZImm(1).addReg(0)
4512 .addGlobalAddress(GV, false, 0);
4513 addFullAddress(BuildMI(BB, X86::MOV32mr, 4+1),AM).addReg(Tmp1);
4515 addFullAddress(BuildMI(BB, X86::MOV32mi, 4+1),AM).addGlobalAddress(GV);
4520 // Check to see if this is a load/op/store combination.
4521 if (TryToFoldLoadOpStore(Node))
4524 switch (N.getOperand(1).getValueType()) {
4525 default: assert(0 && "Cannot store this type!");
4527 case MVT::i8: Opc = X86::MOV8mr; break;
4528 case MVT::i16: Opc = X86::MOV16mr; break;
4529 case MVT::i32: Opc = X86::MOV32mr; break;
4530 case MVT::f32: Opc = X86::MOVSSmr; break;
4531 case MVT::f64: Opc = X86ScalarSSE ? X86::MOVSDmr : X86::FST64m; break;
4534 std::vector<std::pair<unsigned, unsigned> > RP;
4535 RP.push_back(std::make_pair(getRegPressure(N.getOperand(0)), 0));
4536 RP.push_back(std::make_pair(getRegPressure(N.getOperand(1)), 1));
4537 RP.push_back(std::make_pair(getRegPressure(N.getOperand(2)), 2));
4538 std::sort(RP.begin(), RP.end());
4540 Tmp1 = 0; // Silence a warning.
4541 for (unsigned i = 0; i != 3; ++i)
4542 switch (RP[2-i].second) {
4543 default: assert(0 && "Unknown operand number!");
4544 case 0: Select(N.getOperand(0)); break;
4545 case 1: Tmp1 = SelectExpr(N.getOperand(1)); break;
4546 case 2: SelectAddress(N.getOperand(2), AM); break;
4549 addFullAddress(BuildMI(BB, Opc, 4+1), AM).addReg(Tmp1);
4552 case ISD::CALLSEQ_START:
4553 Select(N.getOperand(0));
4555 Tmp1 = cast<ConstantSDNode>(N.getOperand(1))->getValue();
4556 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(Tmp1);
4558 case ISD::CALLSEQ_END:
4559 Select(N.getOperand(0));
4562 Select(N.getOperand(0)); // Select the chain.
4564 (unsigned)cast<ConstantSDNode>(Node->getOperand(4))->getValue();
4565 if (Align == 0) Align = 1;
4567 // Turn the byte code into # iterations
4570 if (ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Node->getOperand(2))) {
4571 unsigned Val = ValC->getValue() & 255;
4573 // If the value is a constant, then we can potentially use larger sets.
4574 switch (Align & 3) {
4575 case 2: // WORD aligned
4576 CountReg = MakeReg(MVT::i32);
4577 if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Node->getOperand(3))) {
4578 BuildMI(BB, X86::MOV32ri, 1, CountReg).addImm(I->getValue()/2);
4580 unsigned ByteReg = SelectExpr(Node->getOperand(3));
4581 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
4583 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
4584 Opcode = X86::REP_STOSW;
4586 case 0: // DWORD aligned
4587 CountReg = MakeReg(MVT::i32);
4588 if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Node->getOperand(3))) {
4589 BuildMI(BB, X86::MOV32ri, 1, CountReg).addImm(I->getValue()/4);
4591 unsigned ByteReg = SelectExpr(Node->getOperand(3));
4592 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
4594 Val = (Val << 8) | Val;
4595 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
4596 Opcode = X86::REP_STOSD;
4598 default: // BYTE aligned
4599 CountReg = SelectExpr(Node->getOperand(3));
4600 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
4601 Opcode = X86::REP_STOSB;
4605 // If it's not a constant value we are storing, just fall back. We could
4606 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
4607 unsigned ValReg = SelectExpr(Node->getOperand(2));
4608 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
4609 CountReg = SelectExpr(Node->getOperand(3));
4610 Opcode = X86::REP_STOSB;
4613 // No matter what the alignment is, we put the source in ESI, the
4614 // destination in EDI, and the count in ECX.
4615 unsigned TmpReg1 = SelectExpr(Node->getOperand(1));
4616 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
4617 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
4618 BuildMI(BB, Opcode, 0);
4622 Select(N.getOperand(0)); // Select the chain.
4624 (unsigned)cast<ConstantSDNode>(Node->getOperand(4))->getValue();
4625 if (Align == 0) Align = 1;
4627 // Turn the byte code into # iterations
4630 switch (Align & 3) {
4631 case 2: // WORD aligned
4632 CountReg = MakeReg(MVT::i32);
4633 if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Node->getOperand(3))) {
4634 BuildMI(BB, X86::MOV32ri, 1, CountReg).addImm(I->getValue()/2);
4636 unsigned ByteReg = SelectExpr(Node->getOperand(3));
4637 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
4639 Opcode = X86::REP_MOVSW;
4641 case 0: // DWORD aligned
4642 CountReg = MakeReg(MVT::i32);
4643 if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Node->getOperand(3))) {
4644 BuildMI(BB, X86::MOV32ri, 1, CountReg).addImm(I->getValue()/4);
4646 unsigned ByteReg = SelectExpr(Node->getOperand(3));
4647 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
4649 Opcode = X86::REP_MOVSD;
4651 default: // BYTE aligned
4652 CountReg = SelectExpr(Node->getOperand(3));
4653 Opcode = X86::REP_MOVSB;
4657 // No matter what the alignment is, we put the source in ESI, the
4658 // destination in EDI, and the count in ECX.
4659 unsigned TmpReg1 = SelectExpr(Node->getOperand(1));
4660 unsigned TmpReg2 = SelectExpr(Node->getOperand(2));
4661 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
4662 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
4663 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
4664 BuildMI(BB, Opcode, 0);
4667 case ISD::WRITEPORT:
4668 if (Node->getOperand(2).getValueType() != MVT::i16) {
4669 std::cerr << "llvm.writeport: Address size is not 16 bits\n";
4672 Select(Node->getOperand(0)); // Emit the chain.
4674 Tmp1 = SelectExpr(Node->getOperand(1));
4675 switch (Node->getOperand(1).getValueType()) {
4677 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(Tmp1);
4678 Tmp2 = X86::OUT8ir; Opc = X86::OUT8rr;
4681 BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(Tmp1);
4682 Tmp2 = X86::OUT16ir; Opc = X86::OUT16rr;
4685 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Tmp1);
4686 Tmp2 = X86::OUT32ir; Opc = X86::OUT32rr;
4689 std::cerr << "llvm.writeport: invalid data type for X86 target";
4693 // If the port is a single-byte constant, use the immediate form.
4694 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Node->getOperand(2)))
4695 if ((CN->getValue() & 255) == CN->getValue()) {
4696 BuildMI(BB, Tmp2, 1).addImm(CN->getValue());
4700 // Otherwise, move the I/O port address into the DX register.
4701 unsigned Reg = SelectExpr(Node->getOperand(2));
4702 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
4703 BuildMI(BB, Opc, 0);
4706 assert(0 && "Should not be reached!");
4710 /// createX86PatternInstructionSelector - This pass converts an LLVM function
4711 /// into a machine code representation using pattern matching and a machine
4712 /// description file.
4714 FunctionPass *llvm::createX86PatternInstructionSelector(TargetMachine &TM) {
4715 return new ISel(TM);