Automatically fold COPY instructions into stack load/store.
[oota-llvm.git] / lib / Target / X86 / X86InstrInfo.cpp
1 //===- X86InstrInfo.cpp - X86 Instruction Information -----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the X86 implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "X86InstrInfo.h"
15 #include "X86.h"
16 #include "X86GenInstrInfo.inc"
17 #include "X86InstrBuilder.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86Subtarget.h"
20 #include "X86TargetMachine.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/LiveVariables.h"
29 #include "llvm/CodeGen/PseudoSourceValue.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/MC/MCAsmInfo.h"
37
38 #include <limits>
39
40 using namespace llvm;
41
42 static cl::opt<bool>
43 NoFusing("disable-spill-fusing",
44          cl::desc("Disable fusing of spill code into instructions"));
45 static cl::opt<bool>
46 PrintFailedFusing("print-failed-fuse-candidates",
47                   cl::desc("Print instructions that the allocator wants to"
48                            " fuse, but the X86 backend currently can't"),
49                   cl::Hidden);
50 static cl::opt<bool>
51 ReMatPICStubLoad("remat-pic-stub-load",
52                  cl::desc("Re-materialize load from stub in PIC mode"),
53                  cl::init(false), cl::Hidden);
54
55 X86InstrInfo::X86InstrInfo(X86TargetMachine &tm)
56   : TargetInstrInfoImpl(X86Insts, array_lengthof(X86Insts)),
57     TM(tm), RI(tm, *this) {
58   SmallVector<unsigned,16> AmbEntries;
59   static const unsigned OpTbl2Addr[][2] = {
60     { X86::ADC32ri,     X86::ADC32mi },
61     { X86::ADC32ri8,    X86::ADC32mi8 },
62     { X86::ADC32rr,     X86::ADC32mr },
63     { X86::ADC64ri32,   X86::ADC64mi32 },
64     { X86::ADC64ri8,    X86::ADC64mi8 },
65     { X86::ADC64rr,     X86::ADC64mr },
66     { X86::ADD16ri,     X86::ADD16mi },
67     { X86::ADD16ri8,    X86::ADD16mi8 },
68     { X86::ADD16rr,     X86::ADD16mr },
69     { X86::ADD32ri,     X86::ADD32mi },
70     { X86::ADD32ri8,    X86::ADD32mi8 },
71     { X86::ADD32rr,     X86::ADD32mr },
72     { X86::ADD64ri32,   X86::ADD64mi32 },
73     { X86::ADD64ri8,    X86::ADD64mi8 },
74     { X86::ADD64rr,     X86::ADD64mr },
75     { X86::ADD8ri,      X86::ADD8mi },
76     { X86::ADD8rr,      X86::ADD8mr },
77     { X86::AND16ri,     X86::AND16mi },
78     { X86::AND16ri8,    X86::AND16mi8 },
79     { X86::AND16rr,     X86::AND16mr },
80     { X86::AND32ri,     X86::AND32mi },
81     { X86::AND32ri8,    X86::AND32mi8 },
82     { X86::AND32rr,     X86::AND32mr },
83     { X86::AND64ri32,   X86::AND64mi32 },
84     { X86::AND64ri8,    X86::AND64mi8 },
85     { X86::AND64rr,     X86::AND64mr },
86     { X86::AND8ri,      X86::AND8mi },
87     { X86::AND8rr,      X86::AND8mr },
88     { X86::DEC16r,      X86::DEC16m },
89     { X86::DEC32r,      X86::DEC32m },
90     { X86::DEC64_16r,   X86::DEC64_16m },
91     { X86::DEC64_32r,   X86::DEC64_32m },
92     { X86::DEC64r,      X86::DEC64m },
93     { X86::DEC8r,       X86::DEC8m },
94     { X86::INC16r,      X86::INC16m },
95     { X86::INC32r,      X86::INC32m },
96     { X86::INC64_16r,   X86::INC64_16m },
97     { X86::INC64_32r,   X86::INC64_32m },
98     { X86::INC64r,      X86::INC64m },
99     { X86::INC8r,       X86::INC8m },
100     { X86::NEG16r,      X86::NEG16m },
101     { X86::NEG32r,      X86::NEG32m },
102     { X86::NEG64r,      X86::NEG64m },
103     { X86::NEG8r,       X86::NEG8m },
104     { X86::NOT16r,      X86::NOT16m },
105     { X86::NOT32r,      X86::NOT32m },
106     { X86::NOT64r,      X86::NOT64m },
107     { X86::NOT8r,       X86::NOT8m },
108     { X86::OR16ri,      X86::OR16mi },
109     { X86::OR16ri8,     X86::OR16mi8 },
110     { X86::OR16rr,      X86::OR16mr },
111     { X86::OR32ri,      X86::OR32mi },
112     { X86::OR32ri8,     X86::OR32mi8 },
113     { X86::OR32rr,      X86::OR32mr },
114     { X86::OR64ri32,    X86::OR64mi32 },
115     { X86::OR64ri8,     X86::OR64mi8 },
116     { X86::OR64rr,      X86::OR64mr },
117     { X86::OR8ri,       X86::OR8mi },
118     { X86::OR8rr,       X86::OR8mr },
119     { X86::ROL16r1,     X86::ROL16m1 },
120     { X86::ROL16rCL,    X86::ROL16mCL },
121     { X86::ROL16ri,     X86::ROL16mi },
122     { X86::ROL32r1,     X86::ROL32m1 },
123     { X86::ROL32rCL,    X86::ROL32mCL },
124     { X86::ROL32ri,     X86::ROL32mi },
125     { X86::ROL64r1,     X86::ROL64m1 },
126     { X86::ROL64rCL,    X86::ROL64mCL },
127     { X86::ROL64ri,     X86::ROL64mi },
128     { X86::ROL8r1,      X86::ROL8m1 },
129     { X86::ROL8rCL,     X86::ROL8mCL },
130     { X86::ROL8ri,      X86::ROL8mi },
131     { X86::ROR16r1,     X86::ROR16m1 },
132     { X86::ROR16rCL,    X86::ROR16mCL },
133     { X86::ROR16ri,     X86::ROR16mi },
134     { X86::ROR32r1,     X86::ROR32m1 },
135     { X86::ROR32rCL,    X86::ROR32mCL },
136     { X86::ROR32ri,     X86::ROR32mi },
137     { X86::ROR64r1,     X86::ROR64m1 },
138     { X86::ROR64rCL,    X86::ROR64mCL },
139     { X86::ROR64ri,     X86::ROR64mi },
140     { X86::ROR8r1,      X86::ROR8m1 },
141     { X86::ROR8rCL,     X86::ROR8mCL },
142     { X86::ROR8ri,      X86::ROR8mi },
143     { X86::SAR16r1,     X86::SAR16m1 },
144     { X86::SAR16rCL,    X86::SAR16mCL },
145     { X86::SAR16ri,     X86::SAR16mi },
146     { X86::SAR32r1,     X86::SAR32m1 },
147     { X86::SAR32rCL,    X86::SAR32mCL },
148     { X86::SAR32ri,     X86::SAR32mi },
149     { X86::SAR64r1,     X86::SAR64m1 },
150     { X86::SAR64rCL,    X86::SAR64mCL },
151     { X86::SAR64ri,     X86::SAR64mi },
152     { X86::SAR8r1,      X86::SAR8m1 },
153     { X86::SAR8rCL,     X86::SAR8mCL },
154     { X86::SAR8ri,      X86::SAR8mi },
155     { X86::SBB32ri,     X86::SBB32mi },
156     { X86::SBB32ri8,    X86::SBB32mi8 },
157     { X86::SBB32rr,     X86::SBB32mr },
158     { X86::SBB64ri32,   X86::SBB64mi32 },
159     { X86::SBB64ri8,    X86::SBB64mi8 },
160     { X86::SBB64rr,     X86::SBB64mr },
161     { X86::SHL16rCL,    X86::SHL16mCL },
162     { X86::SHL16ri,     X86::SHL16mi },
163     { X86::SHL32rCL,    X86::SHL32mCL },
164     { X86::SHL32ri,     X86::SHL32mi },
165     { X86::SHL64rCL,    X86::SHL64mCL },
166     { X86::SHL64ri,     X86::SHL64mi },
167     { X86::SHL8rCL,     X86::SHL8mCL },
168     { X86::SHL8ri,      X86::SHL8mi },
169     { X86::SHLD16rrCL,  X86::SHLD16mrCL },
170     { X86::SHLD16rri8,  X86::SHLD16mri8 },
171     { X86::SHLD32rrCL,  X86::SHLD32mrCL },
172     { X86::SHLD32rri8,  X86::SHLD32mri8 },
173     { X86::SHLD64rrCL,  X86::SHLD64mrCL },
174     { X86::SHLD64rri8,  X86::SHLD64mri8 },
175     { X86::SHR16r1,     X86::SHR16m1 },
176     { X86::SHR16rCL,    X86::SHR16mCL },
177     { X86::SHR16ri,     X86::SHR16mi },
178     { X86::SHR32r1,     X86::SHR32m1 },
179     { X86::SHR32rCL,    X86::SHR32mCL },
180     { X86::SHR32ri,     X86::SHR32mi },
181     { X86::SHR64r1,     X86::SHR64m1 },
182     { X86::SHR64rCL,    X86::SHR64mCL },
183     { X86::SHR64ri,     X86::SHR64mi },
184     { X86::SHR8r1,      X86::SHR8m1 },
185     { X86::SHR8rCL,     X86::SHR8mCL },
186     { X86::SHR8ri,      X86::SHR8mi },
187     { X86::SHRD16rrCL,  X86::SHRD16mrCL },
188     { X86::SHRD16rri8,  X86::SHRD16mri8 },
189     { X86::SHRD32rrCL,  X86::SHRD32mrCL },
190     { X86::SHRD32rri8,  X86::SHRD32mri8 },
191     { X86::SHRD64rrCL,  X86::SHRD64mrCL },
192     { X86::SHRD64rri8,  X86::SHRD64mri8 },
193     { X86::SUB16ri,     X86::SUB16mi },
194     { X86::SUB16ri8,    X86::SUB16mi8 },
195     { X86::SUB16rr,     X86::SUB16mr },
196     { X86::SUB32ri,     X86::SUB32mi },
197     { X86::SUB32ri8,    X86::SUB32mi8 },
198     { X86::SUB32rr,     X86::SUB32mr },
199     { X86::SUB64ri32,   X86::SUB64mi32 },
200     { X86::SUB64ri8,    X86::SUB64mi8 },
201     { X86::SUB64rr,     X86::SUB64mr },
202     { X86::SUB8ri,      X86::SUB8mi },
203     { X86::SUB8rr,      X86::SUB8mr },
204     { X86::XOR16ri,     X86::XOR16mi },
205     { X86::XOR16ri8,    X86::XOR16mi8 },
206     { X86::XOR16rr,     X86::XOR16mr },
207     { X86::XOR32ri,     X86::XOR32mi },
208     { X86::XOR32ri8,    X86::XOR32mi8 },
209     { X86::XOR32rr,     X86::XOR32mr },
210     { X86::XOR64ri32,   X86::XOR64mi32 },
211     { X86::XOR64ri8,    X86::XOR64mi8 },
212     { X86::XOR64rr,     X86::XOR64mr },
213     { X86::XOR8ri,      X86::XOR8mi },
214     { X86::XOR8rr,      X86::XOR8mr }
215   };
216
217   for (unsigned i = 0, e = array_lengthof(OpTbl2Addr); i != e; ++i) {
218     unsigned RegOp = OpTbl2Addr[i][0];
219     unsigned MemOp = OpTbl2Addr[i][1];
220     if (!RegOp2MemOpTable2Addr.insert(std::make_pair((unsigned*)RegOp,
221                                                std::make_pair(MemOp,0))).second)
222       assert(false && "Duplicated entries?");
223     // Index 0, folded load and store, no alignment requirement.
224     unsigned AuxInfo = 0 | (1 << 4) | (1 << 5);
225     if (!MemOp2RegOpTable.insert(std::make_pair((unsigned*)MemOp,
226                                                 std::make_pair(RegOp,
227                                                               AuxInfo))).second)
228       AmbEntries.push_back(MemOp);
229   }
230
231   // If the third value is 1, then it's folding either a load or a store.
232   static const unsigned OpTbl0[][4] = {
233     { X86::BT16ri8,     X86::BT16mi8, 1, 0 },
234     { X86::BT32ri8,     X86::BT32mi8, 1, 0 },
235     { X86::BT64ri8,     X86::BT64mi8, 1, 0 },
236     { X86::CALL32r,     X86::CALL32m, 1, 0 },
237     { X86::CALL64r,     X86::CALL64m, 1, 0 },
238     { X86::CMP16ri,     X86::CMP16mi, 1, 0 },
239     { X86::CMP16ri8,    X86::CMP16mi8, 1, 0 },
240     { X86::CMP16rr,     X86::CMP16mr, 1, 0 },
241     { X86::CMP32ri,     X86::CMP32mi, 1, 0 },
242     { X86::CMP32ri8,    X86::CMP32mi8, 1, 0 },
243     { X86::CMP32rr,     X86::CMP32mr, 1, 0 },
244     { X86::CMP64ri32,   X86::CMP64mi32, 1, 0 },
245     { X86::CMP64ri8,    X86::CMP64mi8, 1, 0 },
246     { X86::CMP64rr,     X86::CMP64mr, 1, 0 },
247     { X86::CMP8ri,      X86::CMP8mi, 1, 0 },
248     { X86::CMP8rr,      X86::CMP8mr, 1, 0 },
249     { X86::DIV16r,      X86::DIV16m, 1, 0 },
250     { X86::DIV32r,      X86::DIV32m, 1, 0 },
251     { X86::DIV64r,      X86::DIV64m, 1, 0 },
252     { X86::DIV8r,       X86::DIV8m, 1, 0 },
253     { X86::EXTRACTPSrr, X86::EXTRACTPSmr, 0, 16 },
254     { X86::FsMOVAPDrr,  X86::MOVSDmr, 0, 0 },
255     { X86::FsMOVAPSrr,  X86::MOVSSmr, 0, 0 },
256     { X86::IDIV16r,     X86::IDIV16m, 1, 0 },
257     { X86::IDIV32r,     X86::IDIV32m, 1, 0 },
258     { X86::IDIV64r,     X86::IDIV64m, 1, 0 },
259     { X86::IDIV8r,      X86::IDIV8m, 1, 0 },
260     { X86::IMUL16r,     X86::IMUL16m, 1, 0 },
261     { X86::IMUL32r,     X86::IMUL32m, 1, 0 },
262     { X86::IMUL64r,     X86::IMUL64m, 1, 0 },
263     { X86::IMUL8r,      X86::IMUL8m, 1, 0 },
264     { X86::JMP32r,      X86::JMP32m, 1, 0 },
265     { X86::JMP64r,      X86::JMP64m, 1, 0 },
266     { X86::MOV16ri,     X86::MOV16mi, 0, 0 },
267     { X86::MOV16rr,     X86::MOV16mr, 0, 0 },
268     { X86::MOV32ri,     X86::MOV32mi, 0, 0 },
269     { X86::MOV32rr,     X86::MOV32mr, 0, 0 },
270     { X86::MOV32rr_TC,  X86::MOV32mr_TC, 0, 0 },
271     { X86::MOV64ri32,   X86::MOV64mi32, 0, 0 },
272     { X86::MOV64rr,     X86::MOV64mr, 0, 0 },
273     { X86::MOV8ri,      X86::MOV8mi, 0, 0 },
274     { X86::MOV8rr,      X86::MOV8mr, 0, 0 },
275     { X86::MOV8rr_NOREX, X86::MOV8mr_NOREX, 0, 0 },
276     { X86::MOVAPDrr,    X86::MOVAPDmr, 0, 16 },
277     { X86::MOVAPSrr,    X86::MOVAPSmr, 0, 16 },
278     { X86::MOVDQArr,    X86::MOVDQAmr, 0, 16 },
279     { X86::MOVPDI2DIrr, X86::MOVPDI2DImr, 0, 0 },
280     { X86::MOVPQIto64rr,X86::MOVPQI2QImr, 0, 0 },
281     { X86::MOVSDto64rr, X86::MOVSDto64mr, 0, 0 },
282     { X86::MOVSS2DIrr,  X86::MOVSS2DImr, 0, 0 },
283     { X86::MOVUPDrr,    X86::MOVUPDmr, 0, 0 },
284     { X86::MOVUPSrr,    X86::MOVUPSmr, 0, 0 },
285     { X86::MUL16r,      X86::MUL16m, 1, 0 },
286     { X86::MUL32r,      X86::MUL32m, 1, 0 },
287     { X86::MUL64r,      X86::MUL64m, 1, 0 },
288     { X86::MUL8r,       X86::MUL8m, 1, 0 },
289     { X86::SETAEr,      X86::SETAEm, 0, 0 },
290     { X86::SETAr,       X86::SETAm, 0, 0 },
291     { X86::SETBEr,      X86::SETBEm, 0, 0 },
292     { X86::SETBr,       X86::SETBm, 0, 0 },
293     { X86::SETEr,       X86::SETEm, 0, 0 },
294     { X86::SETGEr,      X86::SETGEm, 0, 0 },
295     { X86::SETGr,       X86::SETGm, 0, 0 },
296     { X86::SETLEr,      X86::SETLEm, 0, 0 },
297     { X86::SETLr,       X86::SETLm, 0, 0 },
298     { X86::SETNEr,      X86::SETNEm, 0, 0 },
299     { X86::SETNOr,      X86::SETNOm, 0, 0 },
300     { X86::SETNPr,      X86::SETNPm, 0, 0 },
301     { X86::SETNSr,      X86::SETNSm, 0, 0 },
302     { X86::SETOr,       X86::SETOm, 0, 0 },
303     { X86::SETPr,       X86::SETPm, 0, 0 },
304     { X86::SETSr,       X86::SETSm, 0, 0 },
305     { X86::TAILJMPr,    X86::TAILJMPm, 1, 0 },
306     { X86::TAILJMPr64,  X86::TAILJMPm64, 1, 0 },
307     { X86::TEST16ri,    X86::TEST16mi, 1, 0 },
308     { X86::TEST32ri,    X86::TEST32mi, 1, 0 },
309     { X86::TEST64ri32,  X86::TEST64mi32, 1, 0 },
310     { X86::TEST8ri,     X86::TEST8mi, 1, 0 }
311   };
312
313   for (unsigned i = 0, e = array_lengthof(OpTbl0); i != e; ++i) {
314     unsigned RegOp = OpTbl0[i][0];
315     unsigned MemOp = OpTbl0[i][1];
316     unsigned Align = OpTbl0[i][3];
317     if (!RegOp2MemOpTable0.insert(std::make_pair((unsigned*)RegOp,
318                                            std::make_pair(MemOp,Align))).second)
319       assert(false && "Duplicated entries?");
320     unsigned FoldedLoad = OpTbl0[i][2];
321     // Index 0, folded load or store.
322     unsigned AuxInfo = 0 | (FoldedLoad << 4) | ((FoldedLoad^1) << 5);
323     if (RegOp != X86::FsMOVAPDrr && RegOp != X86::FsMOVAPSrr)
324       if (!MemOp2RegOpTable.insert(std::make_pair((unsigned*)MemOp,
325                                      std::make_pair(RegOp, AuxInfo))).second)
326         AmbEntries.push_back(MemOp);
327   }
328
329   static const unsigned OpTbl1[][3] = {
330     { X86::CMP16rr,         X86::CMP16rm, 0 },
331     { X86::CMP32rr,         X86::CMP32rm, 0 },
332     { X86::CMP64rr,         X86::CMP64rm, 0 },
333     { X86::CMP8rr,          X86::CMP8rm, 0 },
334     { X86::CVTSD2SSrr,      X86::CVTSD2SSrm, 0 },
335     { X86::CVTSI2SD64rr,    X86::CVTSI2SD64rm, 0 },
336     { X86::CVTSI2SDrr,      X86::CVTSI2SDrm, 0 },
337     { X86::CVTSI2SS64rr,    X86::CVTSI2SS64rm, 0 },
338     { X86::CVTSI2SSrr,      X86::CVTSI2SSrm, 0 },
339     { X86::CVTSS2SDrr,      X86::CVTSS2SDrm, 0 },
340     { X86::CVTTSD2SI64rr,   X86::CVTTSD2SI64rm, 0 },
341     { X86::CVTTSD2SIrr,     X86::CVTTSD2SIrm, 0 },
342     { X86::CVTTSS2SI64rr,   X86::CVTTSS2SI64rm, 0 },
343     { X86::CVTTSS2SIrr,     X86::CVTTSS2SIrm, 0 },
344     { X86::FsMOVAPDrr,      X86::MOVSDrm, 0 },
345     { X86::FsMOVAPSrr,      X86::MOVSSrm, 0 },
346     { X86::IMUL16rri,       X86::IMUL16rmi, 0 },
347     { X86::IMUL16rri8,      X86::IMUL16rmi8, 0 },
348     { X86::IMUL32rri,       X86::IMUL32rmi, 0 },
349     { X86::IMUL32rri8,      X86::IMUL32rmi8, 0 },
350     { X86::IMUL64rri32,     X86::IMUL64rmi32, 0 },
351     { X86::IMUL64rri8,      X86::IMUL64rmi8, 0 },
352     { X86::Int_CMPSDrr,     X86::Int_CMPSDrm, 0 },
353     { X86::Int_CMPSSrr,     X86::Int_CMPSSrm, 0 },
354     { X86::Int_COMISDrr,    X86::Int_COMISDrm, 0 },
355     { X86::Int_COMISSrr,    X86::Int_COMISSrm, 0 },
356     { X86::Int_CVTDQ2PDrr,  X86::Int_CVTDQ2PDrm, 16 },
357     { X86::Int_CVTDQ2PSrr,  X86::Int_CVTDQ2PSrm, 16 },
358     { X86::Int_CVTPD2DQrr,  X86::Int_CVTPD2DQrm, 16 },
359     { X86::Int_CVTPD2PSrr,  X86::Int_CVTPD2PSrm, 16 },
360     { X86::Int_CVTPS2DQrr,  X86::Int_CVTPS2DQrm, 16 },
361     { X86::Int_CVTPS2PDrr,  X86::Int_CVTPS2PDrm, 0 },
362     { X86::Int_CVTSD2SI64rr,X86::Int_CVTSD2SI64rm, 0 },
363     { X86::Int_CVTSD2SIrr,  X86::Int_CVTSD2SIrm, 0 },
364     { X86::Int_CVTSD2SSrr,  X86::Int_CVTSD2SSrm, 0 },
365     { X86::Int_CVTSI2SD64rr,X86::Int_CVTSI2SD64rm, 0 },
366     { X86::Int_CVTSI2SDrr,  X86::Int_CVTSI2SDrm, 0 },
367     { X86::Int_CVTSI2SS64rr,X86::Int_CVTSI2SS64rm, 0 },
368     { X86::Int_CVTSI2SSrr,  X86::Int_CVTSI2SSrm, 0 },
369     { X86::Int_CVTSS2SDrr,  X86::Int_CVTSS2SDrm, 0 },
370     { X86::Int_CVTSS2SI64rr,X86::Int_CVTSS2SI64rm, 0 },
371     { X86::Int_CVTSS2SIrr,  X86::Int_CVTSS2SIrm, 0 },
372     { X86::Int_CVTTPD2DQrr, X86::Int_CVTTPD2DQrm, 16 },
373     { X86::Int_CVTTPS2DQrr, X86::Int_CVTTPS2DQrm, 16 },
374     { X86::Int_CVTTSD2SI64rr,X86::Int_CVTTSD2SI64rm, 0 },
375     { X86::Int_CVTTSD2SIrr, X86::Int_CVTTSD2SIrm, 0 },
376     { X86::Int_CVTTSS2SI64rr,X86::Int_CVTTSS2SI64rm, 0 },
377     { X86::Int_CVTTSS2SIrr, X86::Int_CVTTSS2SIrm, 0 },
378     { X86::Int_UCOMISDrr,   X86::Int_UCOMISDrm, 0 },
379     { X86::Int_UCOMISSrr,   X86::Int_UCOMISSrm, 0 },
380     { X86::MOV16rr,         X86::MOV16rm, 0 },
381     { X86::MOV32rr,         X86::MOV32rm, 0 },
382     { X86::MOV32rr_TC,      X86::MOV32rm_TC, 0 },
383     { X86::MOV64rr,         X86::MOV64rm, 0 },
384     { X86::MOV64toPQIrr,    X86::MOVQI2PQIrm, 0 },
385     { X86::MOV64toSDrr,     X86::MOV64toSDrm, 0 },
386     { X86::MOV8rr,          X86::MOV8rm, 0 },
387     { X86::MOVAPDrr,        X86::MOVAPDrm, 16 },
388     { X86::MOVAPSrr,        X86::MOVAPSrm, 16 },
389     { X86::MOVDDUPrr,       X86::MOVDDUPrm, 0 },
390     { X86::MOVDI2PDIrr,     X86::MOVDI2PDIrm, 0 },
391     { X86::MOVDI2SSrr,      X86::MOVDI2SSrm, 0 },
392     { X86::MOVDQArr,        X86::MOVDQArm, 16 },
393     { X86::MOVSHDUPrr,      X86::MOVSHDUPrm, 16 },
394     { X86::MOVSLDUPrr,      X86::MOVSLDUPrm, 16 },
395     { X86::MOVSX16rr8,      X86::MOVSX16rm8, 0 },
396     { X86::MOVSX32rr16,     X86::MOVSX32rm16, 0 },
397     { X86::MOVSX32rr8,      X86::MOVSX32rm8, 0 },
398     { X86::MOVSX64rr16,     X86::MOVSX64rm16, 0 },
399     { X86::MOVSX64rr32,     X86::MOVSX64rm32, 0 },
400     { X86::MOVSX64rr8,      X86::MOVSX64rm8, 0 },
401     { X86::MOVUPDrr,        X86::MOVUPDrm, 16 },
402     { X86::MOVUPSrr,        X86::MOVUPSrm, 0 },
403     { X86::MOVZDI2PDIrr,    X86::MOVZDI2PDIrm, 0 },
404     { X86::MOVZQI2PQIrr,    X86::MOVZQI2PQIrm, 0 },
405     { X86::MOVZPQILo2PQIrr, X86::MOVZPQILo2PQIrm, 16 },
406     { X86::MOVZX16rr8,      X86::MOVZX16rm8, 0 },
407     { X86::MOVZX32rr16,     X86::MOVZX32rm16, 0 },
408     { X86::MOVZX32_NOREXrr8, X86::MOVZX32_NOREXrm8, 0 },
409     { X86::MOVZX32rr8,      X86::MOVZX32rm8, 0 },
410     { X86::MOVZX64rr16,     X86::MOVZX64rm16, 0 },
411     { X86::MOVZX64rr32,     X86::MOVZX64rm32, 0 },
412     { X86::MOVZX64rr8,      X86::MOVZX64rm8, 0 },
413     { X86::PSHUFDri,        X86::PSHUFDmi, 16 },
414     { X86::PSHUFHWri,       X86::PSHUFHWmi, 16 },
415     { X86::PSHUFLWri,       X86::PSHUFLWmi, 16 },
416     { X86::RCPPSr,          X86::RCPPSm, 16 },
417     { X86::RCPPSr_Int,      X86::RCPPSm_Int, 16 },
418     { X86::RSQRTPSr,        X86::RSQRTPSm, 16 },
419     { X86::RSQRTPSr_Int,    X86::RSQRTPSm_Int, 16 },
420     { X86::RSQRTSSr,        X86::RSQRTSSm, 0 },
421     { X86::RSQRTSSr_Int,    X86::RSQRTSSm_Int, 0 },
422     { X86::SQRTPDr,         X86::SQRTPDm, 16 },
423     { X86::SQRTPDr_Int,     X86::SQRTPDm_Int, 16 },
424     { X86::SQRTPSr,         X86::SQRTPSm, 16 },
425     { X86::SQRTPSr_Int,     X86::SQRTPSm_Int, 16 },
426     { X86::SQRTSDr,         X86::SQRTSDm, 0 },
427     { X86::SQRTSDr_Int,     X86::SQRTSDm_Int, 0 },
428     { X86::SQRTSSr,         X86::SQRTSSm, 0 },
429     { X86::SQRTSSr_Int,     X86::SQRTSSm_Int, 0 },
430     { X86::TEST16rr,        X86::TEST16rm, 0 },
431     { X86::TEST32rr,        X86::TEST32rm, 0 },
432     { X86::TEST64rr,        X86::TEST64rm, 0 },
433     { X86::TEST8rr,         X86::TEST8rm, 0 },
434     // FIXME: TEST*rr EAX,EAX ---> CMP [mem], 0
435     { X86::UCOMISDrr,       X86::UCOMISDrm, 0 },
436     { X86::UCOMISSrr,       X86::UCOMISSrm, 0 }
437   };
438
439   for (unsigned i = 0, e = array_lengthof(OpTbl1); i != e; ++i) {
440     unsigned RegOp = OpTbl1[i][0];
441     unsigned MemOp = OpTbl1[i][1];
442     unsigned Align = OpTbl1[i][2];
443     if (!RegOp2MemOpTable1.insert(std::make_pair((unsigned*)RegOp,
444                                            std::make_pair(MemOp,Align))).second)
445       assert(false && "Duplicated entries?");
446     // Index 1, folded load
447     unsigned AuxInfo = 1 | (1 << 4);
448     if (RegOp != X86::FsMOVAPDrr && RegOp != X86::FsMOVAPSrr)
449       if (!MemOp2RegOpTable.insert(std::make_pair((unsigned*)MemOp,
450                                      std::make_pair(RegOp, AuxInfo))).second)
451         AmbEntries.push_back(MemOp);
452   }
453
454   static const unsigned OpTbl2[][3] = {
455     { X86::ADC32rr,         X86::ADC32rm, 0 },
456     { X86::ADC64rr,         X86::ADC64rm, 0 },
457     { X86::ADD16rr,         X86::ADD16rm, 0 },
458     { X86::ADD32rr,         X86::ADD32rm, 0 },
459     { X86::ADD64rr,         X86::ADD64rm, 0 },
460     { X86::ADD8rr,          X86::ADD8rm, 0 },
461     { X86::ADDPDrr,         X86::ADDPDrm, 16 },
462     { X86::ADDPSrr,         X86::ADDPSrm, 16 },
463     { X86::ADDSDrr,         X86::ADDSDrm, 0 },
464     { X86::ADDSSrr,         X86::ADDSSrm, 0 },
465     { X86::ADDSUBPDrr,      X86::ADDSUBPDrm, 16 },
466     { X86::ADDSUBPSrr,      X86::ADDSUBPSrm, 16 },
467     { X86::AND16rr,         X86::AND16rm, 0 },
468     { X86::AND32rr,         X86::AND32rm, 0 },
469     { X86::AND64rr,         X86::AND64rm, 0 },
470     { X86::AND8rr,          X86::AND8rm, 0 },
471     { X86::ANDNPDrr,        X86::ANDNPDrm, 16 },
472     { X86::ANDNPSrr,        X86::ANDNPSrm, 16 },
473     { X86::ANDPDrr,         X86::ANDPDrm, 16 },
474     { X86::ANDPSrr,         X86::ANDPSrm, 16 },
475     { X86::CMOVA16rr,       X86::CMOVA16rm, 0 },
476     { X86::CMOVA32rr,       X86::CMOVA32rm, 0 },
477     { X86::CMOVA64rr,       X86::CMOVA64rm, 0 },
478     { X86::CMOVAE16rr,      X86::CMOVAE16rm, 0 },
479     { X86::CMOVAE32rr,      X86::CMOVAE32rm, 0 },
480     { X86::CMOVAE64rr,      X86::CMOVAE64rm, 0 },
481     { X86::CMOVB16rr,       X86::CMOVB16rm, 0 },
482     { X86::CMOVB32rr,       X86::CMOVB32rm, 0 },
483     { X86::CMOVB64rr,       X86::CMOVB64rm, 0 },
484     { X86::CMOVBE16rr,      X86::CMOVBE16rm, 0 },
485     { X86::CMOVBE32rr,      X86::CMOVBE32rm, 0 },
486     { X86::CMOVBE64rr,      X86::CMOVBE64rm, 0 },
487     { X86::CMOVE16rr,       X86::CMOVE16rm, 0 },
488     { X86::CMOVE32rr,       X86::CMOVE32rm, 0 },
489     { X86::CMOVE64rr,       X86::CMOVE64rm, 0 },
490     { X86::CMOVG16rr,       X86::CMOVG16rm, 0 },
491     { X86::CMOVG32rr,       X86::CMOVG32rm, 0 },
492     { X86::CMOVG64rr,       X86::CMOVG64rm, 0 },
493     { X86::CMOVGE16rr,      X86::CMOVGE16rm, 0 },
494     { X86::CMOVGE32rr,      X86::CMOVGE32rm, 0 },
495     { X86::CMOVGE64rr,      X86::CMOVGE64rm, 0 },
496     { X86::CMOVL16rr,       X86::CMOVL16rm, 0 },
497     { X86::CMOVL32rr,       X86::CMOVL32rm, 0 },
498     { X86::CMOVL64rr,       X86::CMOVL64rm, 0 },
499     { X86::CMOVLE16rr,      X86::CMOVLE16rm, 0 },
500     { X86::CMOVLE32rr,      X86::CMOVLE32rm, 0 },
501     { X86::CMOVLE64rr,      X86::CMOVLE64rm, 0 },
502     { X86::CMOVNE16rr,      X86::CMOVNE16rm, 0 },
503     { X86::CMOVNE32rr,      X86::CMOVNE32rm, 0 },
504     { X86::CMOVNE64rr,      X86::CMOVNE64rm, 0 },
505     { X86::CMOVNO16rr,      X86::CMOVNO16rm, 0 },
506     { X86::CMOVNO32rr,      X86::CMOVNO32rm, 0 },
507     { X86::CMOVNO64rr,      X86::CMOVNO64rm, 0 },
508     { X86::CMOVNP16rr,      X86::CMOVNP16rm, 0 },
509     { X86::CMOVNP32rr,      X86::CMOVNP32rm, 0 },
510     { X86::CMOVNP64rr,      X86::CMOVNP64rm, 0 },
511     { X86::CMOVNS16rr,      X86::CMOVNS16rm, 0 },
512     { X86::CMOVNS32rr,      X86::CMOVNS32rm, 0 },
513     { X86::CMOVNS64rr,      X86::CMOVNS64rm, 0 },
514     { X86::CMOVO16rr,       X86::CMOVO16rm, 0 },
515     { X86::CMOVO32rr,       X86::CMOVO32rm, 0 },
516     { X86::CMOVO64rr,       X86::CMOVO64rm, 0 },
517     { X86::CMOVP16rr,       X86::CMOVP16rm, 0 },
518     { X86::CMOVP32rr,       X86::CMOVP32rm, 0 },
519     { X86::CMOVP64rr,       X86::CMOVP64rm, 0 },
520     { X86::CMOVS16rr,       X86::CMOVS16rm, 0 },
521     { X86::CMOVS32rr,       X86::CMOVS32rm, 0 },
522     { X86::CMOVS64rr,       X86::CMOVS64rm, 0 },
523     { X86::CMPPDrri,        X86::CMPPDrmi, 16 },
524     { X86::CMPPSrri,        X86::CMPPSrmi, 16 },
525     { X86::CMPSDrr,         X86::CMPSDrm, 0 },
526     { X86::CMPSSrr,         X86::CMPSSrm, 0 },
527     { X86::DIVPDrr,         X86::DIVPDrm, 16 },
528     { X86::DIVPSrr,         X86::DIVPSrm, 16 },
529     { X86::DIVSDrr,         X86::DIVSDrm, 0 },
530     { X86::DIVSSrr,         X86::DIVSSrm, 0 },
531     { X86::FsANDNPDrr,      X86::FsANDNPDrm, 16 },
532     { X86::FsANDNPSrr,      X86::FsANDNPSrm, 16 },
533     { X86::FsANDPDrr,       X86::FsANDPDrm, 16 },
534     { X86::FsANDPSrr,       X86::FsANDPSrm, 16 },
535     { X86::FsORPDrr,        X86::FsORPDrm, 16 },
536     { X86::FsORPSrr,        X86::FsORPSrm, 16 },
537     { X86::FsXORPDrr,       X86::FsXORPDrm, 16 },
538     { X86::FsXORPSrr,       X86::FsXORPSrm, 16 },
539     { X86::HADDPDrr,        X86::HADDPDrm, 16 },
540     { X86::HADDPSrr,        X86::HADDPSrm, 16 },
541     { X86::HSUBPDrr,        X86::HSUBPDrm, 16 },
542     { X86::HSUBPSrr,        X86::HSUBPSrm, 16 },
543     { X86::IMUL16rr,        X86::IMUL16rm, 0 },
544     { X86::IMUL32rr,        X86::IMUL32rm, 0 },
545     { X86::IMUL64rr,        X86::IMUL64rm, 0 },
546     { X86::MAXPDrr,         X86::MAXPDrm, 16 },
547     { X86::MAXPDrr_Int,     X86::MAXPDrm_Int, 16 },
548     { X86::MAXPSrr,         X86::MAXPSrm, 16 },
549     { X86::MAXPSrr_Int,     X86::MAXPSrm_Int, 16 },
550     { X86::MAXSDrr,         X86::MAXSDrm, 0 },
551     { X86::MAXSDrr_Int,     X86::MAXSDrm_Int, 0 },
552     { X86::MAXSSrr,         X86::MAXSSrm, 0 },
553     { X86::MAXSSrr_Int,     X86::MAXSSrm_Int, 0 },
554     { X86::MINPDrr,         X86::MINPDrm, 16 },
555     { X86::MINPDrr_Int,     X86::MINPDrm_Int, 16 },
556     { X86::MINPSrr,         X86::MINPSrm, 16 },
557     { X86::MINPSrr_Int,     X86::MINPSrm_Int, 16 },
558     { X86::MINSDrr,         X86::MINSDrm, 0 },
559     { X86::MINSDrr_Int,     X86::MINSDrm_Int, 0 },
560     { X86::MINSSrr,         X86::MINSSrm, 0 },
561     { X86::MINSSrr_Int,     X86::MINSSrm_Int, 0 },
562     { X86::MULPDrr,         X86::MULPDrm, 16 },
563     { X86::MULPSrr,         X86::MULPSrm, 16 },
564     { X86::MULSDrr,         X86::MULSDrm, 0 },
565     { X86::MULSSrr,         X86::MULSSrm, 0 },
566     { X86::OR16rr,          X86::OR16rm, 0 },
567     { X86::OR32rr,          X86::OR32rm, 0 },
568     { X86::OR64rr,          X86::OR64rm, 0 },
569     { X86::OR8rr,           X86::OR8rm, 0 },
570     { X86::ORPDrr,          X86::ORPDrm, 16 },
571     { X86::ORPSrr,          X86::ORPSrm, 16 },
572     { X86::PACKSSDWrr,      X86::PACKSSDWrm, 16 },
573     { X86::PACKSSWBrr,      X86::PACKSSWBrm, 16 },
574     { X86::PACKUSWBrr,      X86::PACKUSWBrm, 16 },
575     { X86::PADDBrr,         X86::PADDBrm, 16 },
576     { X86::PADDDrr,         X86::PADDDrm, 16 },
577     { X86::PADDQrr,         X86::PADDQrm, 16 },
578     { X86::PADDSBrr,        X86::PADDSBrm, 16 },
579     { X86::PADDSWrr,        X86::PADDSWrm, 16 },
580     { X86::PADDWrr,         X86::PADDWrm, 16 },
581     { X86::PANDNrr,         X86::PANDNrm, 16 },
582     { X86::PANDrr,          X86::PANDrm, 16 },
583     { X86::PAVGBrr,         X86::PAVGBrm, 16 },
584     { X86::PAVGWrr,         X86::PAVGWrm, 16 },
585     { X86::PCMPEQBrr,       X86::PCMPEQBrm, 16 },
586     { X86::PCMPEQDrr,       X86::PCMPEQDrm, 16 },
587     { X86::PCMPEQWrr,       X86::PCMPEQWrm, 16 },
588     { X86::PCMPGTBrr,       X86::PCMPGTBrm, 16 },
589     { X86::PCMPGTDrr,       X86::PCMPGTDrm, 16 },
590     { X86::PCMPGTWrr,       X86::PCMPGTWrm, 16 },
591     { X86::PINSRWrri,       X86::PINSRWrmi, 16 },
592     { X86::PMADDWDrr,       X86::PMADDWDrm, 16 },
593     { X86::PMAXSWrr,        X86::PMAXSWrm, 16 },
594     { X86::PMAXUBrr,        X86::PMAXUBrm, 16 },
595     { X86::PMINSWrr,        X86::PMINSWrm, 16 },
596     { X86::PMINUBrr,        X86::PMINUBrm, 16 },
597     { X86::PMULDQrr,        X86::PMULDQrm, 16 },
598     { X86::PMULHUWrr,       X86::PMULHUWrm, 16 },
599     { X86::PMULHWrr,        X86::PMULHWrm, 16 },
600     { X86::PMULLDrr,        X86::PMULLDrm, 16 },
601     { X86::PMULLWrr,        X86::PMULLWrm, 16 },
602     { X86::PMULUDQrr,       X86::PMULUDQrm, 16 },
603     { X86::PORrr,           X86::PORrm, 16 },
604     { X86::PSADBWrr,        X86::PSADBWrm, 16 },
605     { X86::PSLLDrr,         X86::PSLLDrm, 16 },
606     { X86::PSLLQrr,         X86::PSLLQrm, 16 },
607     { X86::PSLLWrr,         X86::PSLLWrm, 16 },
608     { X86::PSRADrr,         X86::PSRADrm, 16 },
609     { X86::PSRAWrr,         X86::PSRAWrm, 16 },
610     { X86::PSRLDrr,         X86::PSRLDrm, 16 },
611     { X86::PSRLQrr,         X86::PSRLQrm, 16 },
612     { X86::PSRLWrr,         X86::PSRLWrm, 16 },
613     { X86::PSUBBrr,         X86::PSUBBrm, 16 },
614     { X86::PSUBDrr,         X86::PSUBDrm, 16 },
615     { X86::PSUBSBrr,        X86::PSUBSBrm, 16 },
616     { X86::PSUBSWrr,        X86::PSUBSWrm, 16 },
617     { X86::PSUBWrr,         X86::PSUBWrm, 16 },
618     { X86::PUNPCKHBWrr,     X86::PUNPCKHBWrm, 16 },
619     { X86::PUNPCKHDQrr,     X86::PUNPCKHDQrm, 16 },
620     { X86::PUNPCKHQDQrr,    X86::PUNPCKHQDQrm, 16 },
621     { X86::PUNPCKHWDrr,     X86::PUNPCKHWDrm, 16 },
622     { X86::PUNPCKLBWrr,     X86::PUNPCKLBWrm, 16 },
623     { X86::PUNPCKLDQrr,     X86::PUNPCKLDQrm, 16 },
624     { X86::PUNPCKLQDQrr,    X86::PUNPCKLQDQrm, 16 },
625     { X86::PUNPCKLWDrr,     X86::PUNPCKLWDrm, 16 },
626     { X86::PXORrr,          X86::PXORrm, 16 },
627     { X86::SBB32rr,         X86::SBB32rm, 0 },
628     { X86::SBB64rr,         X86::SBB64rm, 0 },
629     { X86::SHUFPDrri,       X86::SHUFPDrmi, 16 },
630     { X86::SHUFPSrri,       X86::SHUFPSrmi, 16 },
631     { X86::SUB16rr,         X86::SUB16rm, 0 },
632     { X86::SUB32rr,         X86::SUB32rm, 0 },
633     { X86::SUB64rr,         X86::SUB64rm, 0 },
634     { X86::SUB8rr,          X86::SUB8rm, 0 },
635     { X86::SUBPDrr,         X86::SUBPDrm, 16 },
636     { X86::SUBPSrr,         X86::SUBPSrm, 16 },
637     { X86::SUBSDrr,         X86::SUBSDrm, 0 },
638     { X86::SUBSSrr,         X86::SUBSSrm, 0 },
639     // FIXME: TEST*rr -> swapped operand of TEST*mr.
640     { X86::UNPCKHPDrr,      X86::UNPCKHPDrm, 16 },
641     { X86::UNPCKHPSrr,      X86::UNPCKHPSrm, 16 },
642     { X86::UNPCKLPDrr,      X86::UNPCKLPDrm, 16 },
643     { X86::UNPCKLPSrr,      X86::UNPCKLPSrm, 16 },
644     { X86::XOR16rr,         X86::XOR16rm, 0 },
645     { X86::XOR32rr,         X86::XOR32rm, 0 },
646     { X86::XOR64rr,         X86::XOR64rm, 0 },
647     { X86::XOR8rr,          X86::XOR8rm, 0 },
648     { X86::XORPDrr,         X86::XORPDrm, 16 },
649     { X86::XORPSrr,         X86::XORPSrm, 16 }
650   };
651
652   for (unsigned i = 0, e = array_lengthof(OpTbl2); i != e; ++i) {
653     unsigned RegOp = OpTbl2[i][0];
654     unsigned MemOp = OpTbl2[i][1];
655     unsigned Align = OpTbl2[i][2];
656     if (!RegOp2MemOpTable2.insert(std::make_pair((unsigned*)RegOp,
657                                            std::make_pair(MemOp,Align))).second)
658       assert(false && "Duplicated entries?");
659     // Index 2, folded load
660     unsigned AuxInfo = 2 | (1 << 4);
661     if (!MemOp2RegOpTable.insert(std::make_pair((unsigned*)MemOp,
662                                    std::make_pair(RegOp, AuxInfo))).second)
663       AmbEntries.push_back(MemOp);
664   }
665
666   // Remove ambiguous entries.
667   assert(AmbEntries.empty() && "Duplicated entries in unfolding maps?");
668 }
669
670 bool X86InstrInfo::isMoveInstr(const MachineInstr& MI,
671                                unsigned &SrcReg, unsigned &DstReg,
672                                unsigned &SrcSubIdx, unsigned &DstSubIdx) const {
673   switch (MI.getOpcode()) {
674   default:
675     return false;
676   case X86::MOV8rr:
677   case X86::MOV8rr_NOREX:
678   case X86::MOV16rr:
679   case X86::MOV32rr: 
680   case X86::MOV64rr:
681   case X86::MOV32rr_TC: 
682   case X86::MOV64rr_TC:
683
684   // FP Stack register class copies
685   case X86::MOV_Fp3232: case X86::MOV_Fp6464: case X86::MOV_Fp8080:
686   case X86::MOV_Fp3264: case X86::MOV_Fp3280:
687   case X86::MOV_Fp6432: case X86::MOV_Fp8032:
688
689   // Note that MOVSSrr and MOVSDrr are not considered copies. FR32 and FR64
690   // copies are done with FsMOVAPSrr and FsMOVAPDrr.
691
692   case X86::FsMOVAPSrr:
693   case X86::FsMOVAPDrr:
694   case X86::MOVAPSrr:
695   case X86::MOVAPDrr:
696   case X86::MOVDQArr:
697   case X86::MMX_MOVQ64rr:
698     assert(MI.getNumOperands() >= 2 &&
699            MI.getOperand(0).isReg() &&
700            MI.getOperand(1).isReg() &&
701            "invalid register-register move instruction");
702     SrcReg = MI.getOperand(1).getReg();
703     DstReg = MI.getOperand(0).getReg();
704     SrcSubIdx = MI.getOperand(1).getSubReg();
705     DstSubIdx = MI.getOperand(0).getSubReg();
706     return true;
707   }
708 }
709
710 bool
711 X86InstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
712                                     unsigned &SrcReg, unsigned &DstReg,
713                                     unsigned &SubIdx) const {
714   switch (MI.getOpcode()) {
715   default: break;
716   case X86::MOVSX16rr8:
717   case X86::MOVZX16rr8:
718   case X86::MOVSX32rr8:
719   case X86::MOVZX32rr8:
720   case X86::MOVSX64rr8:
721   case X86::MOVZX64rr8:
722     if (!TM.getSubtarget<X86Subtarget>().is64Bit())
723       // It's not always legal to reference the low 8-bit of the larger
724       // register in 32-bit mode.
725       return false;
726   case X86::MOVSX32rr16:
727   case X86::MOVZX32rr16:
728   case X86::MOVSX64rr16:
729   case X86::MOVZX64rr16:
730   case X86::MOVSX64rr32:
731   case X86::MOVZX64rr32: {
732     if (MI.getOperand(0).getSubReg() || MI.getOperand(1).getSubReg())
733       // Be conservative.
734       return false;
735     SrcReg = MI.getOperand(1).getReg();
736     DstReg = MI.getOperand(0).getReg();
737     switch (MI.getOpcode()) {
738     default:
739       llvm_unreachable(0);
740       break;
741     case X86::MOVSX16rr8:
742     case X86::MOVZX16rr8:
743     case X86::MOVSX32rr8:
744     case X86::MOVZX32rr8:
745     case X86::MOVSX64rr8:
746     case X86::MOVZX64rr8:
747       SubIdx = X86::sub_8bit;
748       break;
749     case X86::MOVSX32rr16:
750     case X86::MOVZX32rr16:
751     case X86::MOVSX64rr16:
752     case X86::MOVZX64rr16:
753       SubIdx = X86::sub_16bit;
754       break;
755     case X86::MOVSX64rr32:
756     case X86::MOVZX64rr32:
757       SubIdx = X86::sub_32bit;
758       break;
759     }
760     return true;
761   }
762   }
763   return false;
764 }
765
766 /// isFrameOperand - Return true and the FrameIndex if the specified
767 /// operand and follow operands form a reference to the stack frame.
768 bool X86InstrInfo::isFrameOperand(const MachineInstr *MI, unsigned int Op,
769                                   int &FrameIndex) const {
770   if (MI->getOperand(Op).isFI() && MI->getOperand(Op+1).isImm() &&
771       MI->getOperand(Op+2).isReg() && MI->getOperand(Op+3).isImm() &&
772       MI->getOperand(Op+1).getImm() == 1 &&
773       MI->getOperand(Op+2).getReg() == 0 &&
774       MI->getOperand(Op+3).getImm() == 0) {
775     FrameIndex = MI->getOperand(Op).getIndex();
776     return true;
777   }
778   return false;
779 }
780
781 static bool isFrameLoadOpcode(int Opcode) {
782   switch (Opcode) {
783   default: break;
784   case X86::MOV8rm:
785   case X86::MOV16rm:
786   case X86::MOV32rm:
787   case X86::MOV64rm:
788   case X86::LD_Fp64m:
789   case X86::MOVSSrm:
790   case X86::MOVSDrm:
791   case X86::MOVAPSrm:
792   case X86::MOVAPDrm:
793   case X86::MOVDQArm:
794   case X86::MMX_MOVD64rm:
795   case X86::MMX_MOVQ64rm:
796     return true;
797     break;
798   }
799   return false;
800 }
801
802 static bool isFrameStoreOpcode(int Opcode) {
803   switch (Opcode) {
804   default: break;
805   case X86::MOV8mr:
806   case X86::MOV16mr:
807   case X86::MOV32mr:
808   case X86::MOV64mr:
809   case X86::ST_FpP64m:
810   case X86::MOVSSmr:
811   case X86::MOVSDmr:
812   case X86::MOVAPSmr:
813   case X86::MOVAPDmr:
814   case X86::MOVDQAmr:
815   case X86::MMX_MOVD64mr:
816   case X86::MMX_MOVQ64mr:
817   case X86::MMX_MOVNTQmr:
818     return true;
819   }
820   return false;
821 }
822
823 unsigned X86InstrInfo::isLoadFromStackSlot(const MachineInstr *MI, 
824                                            int &FrameIndex) const {
825   if (isFrameLoadOpcode(MI->getOpcode()))
826     if (isFrameOperand(MI, 1, FrameIndex))
827       return MI->getOperand(0).getReg();
828   return 0;
829 }
830
831 unsigned X86InstrInfo::isLoadFromStackSlotPostFE(const MachineInstr *MI, 
832                                                  int &FrameIndex) const {
833   if (isFrameLoadOpcode(MI->getOpcode())) {
834     unsigned Reg;
835     if ((Reg = isLoadFromStackSlot(MI, FrameIndex)))
836       return Reg;
837     // Check for post-frame index elimination operations
838     const MachineMemOperand *Dummy;
839     return hasLoadFromStackSlot(MI, Dummy, FrameIndex);
840   }
841   return 0;
842 }
843
844 bool X86InstrInfo::hasLoadFromStackSlot(const MachineInstr *MI,
845                                         const MachineMemOperand *&MMO,
846                                         int &FrameIndex) const {
847   for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
848          oe = MI->memoperands_end();
849        o != oe;
850        ++o) {
851     if ((*o)->isLoad() && (*o)->getValue())
852       if (const FixedStackPseudoSourceValue *Value =
853           dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
854         FrameIndex = Value->getFrameIndex();
855         MMO = *o;
856         return true;
857       }
858   }
859   return false;
860 }
861
862 unsigned X86InstrInfo::isStoreToStackSlot(const MachineInstr *MI,
863                                           int &FrameIndex) const {
864   if (isFrameStoreOpcode(MI->getOpcode()))
865     if (isFrameOperand(MI, 0, FrameIndex))
866       return MI->getOperand(X86::AddrNumOperands).getReg();
867   return 0;
868 }
869
870 unsigned X86InstrInfo::isStoreToStackSlotPostFE(const MachineInstr *MI,
871                                                 int &FrameIndex) const {
872   if (isFrameStoreOpcode(MI->getOpcode())) {
873     unsigned Reg;
874     if ((Reg = isStoreToStackSlot(MI, FrameIndex)))
875       return Reg;
876     // Check for post-frame index elimination operations
877     const MachineMemOperand *Dummy;
878     return hasStoreToStackSlot(MI, Dummy, FrameIndex);
879   }
880   return 0;
881 }
882
883 bool X86InstrInfo::hasStoreToStackSlot(const MachineInstr *MI,
884                                        const MachineMemOperand *&MMO,
885                                        int &FrameIndex) const {
886   for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
887          oe = MI->memoperands_end();
888        o != oe;
889        ++o) {
890     if ((*o)->isStore() && (*o)->getValue())
891       if (const FixedStackPseudoSourceValue *Value =
892           dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
893         FrameIndex = Value->getFrameIndex();
894         MMO = *o;
895         return true;
896       }
897   }
898   return false;
899 }
900
901 /// regIsPICBase - Return true if register is PIC base (i.e.g defined by
902 /// X86::MOVPC32r.
903 static bool regIsPICBase(unsigned BaseReg, const MachineRegisterInfo &MRI) {
904   bool isPICBase = false;
905   for (MachineRegisterInfo::def_iterator I = MRI.def_begin(BaseReg),
906          E = MRI.def_end(); I != E; ++I) {
907     MachineInstr *DefMI = I.getOperand().getParent();
908     if (DefMI->getOpcode() != X86::MOVPC32r)
909       return false;
910     assert(!isPICBase && "More than one PIC base?");
911     isPICBase = true;
912   }
913   return isPICBase;
914 }
915
916 bool
917 X86InstrInfo::isReallyTriviallyReMaterializable(const MachineInstr *MI,
918                                                 AliasAnalysis *AA) const {
919   switch (MI->getOpcode()) {
920   default: break;
921     case X86::MOV8rm:
922     case X86::MOV16rm:
923     case X86::MOV32rm:
924     case X86::MOV64rm:
925     case X86::LD_Fp64m:
926     case X86::MOVSSrm:
927     case X86::MOVSDrm:
928     case X86::MOVAPSrm:
929     case X86::MOVUPSrm:
930     case X86::MOVUPSrm_Int:
931     case X86::MOVAPDrm:
932     case X86::MOVDQArm:
933     case X86::MMX_MOVD64rm:
934     case X86::MMX_MOVQ64rm:
935     case X86::FsMOVAPSrm:
936     case X86::FsMOVAPDrm: {
937       // Loads from constant pools are trivially rematerializable.
938       if (MI->getOperand(1).isReg() &&
939           MI->getOperand(2).isImm() &&
940           MI->getOperand(3).isReg() && MI->getOperand(3).getReg() == 0 &&
941           MI->isInvariantLoad(AA)) {
942         unsigned BaseReg = MI->getOperand(1).getReg();
943         if (BaseReg == 0 || BaseReg == X86::RIP)
944           return true;
945         // Allow re-materialization of PIC load.
946         if (!ReMatPICStubLoad && MI->getOperand(4).isGlobal())
947           return false;
948         const MachineFunction &MF = *MI->getParent()->getParent();
949         const MachineRegisterInfo &MRI = MF.getRegInfo();
950         bool isPICBase = false;
951         for (MachineRegisterInfo::def_iterator I = MRI.def_begin(BaseReg),
952                E = MRI.def_end(); I != E; ++I) {
953           MachineInstr *DefMI = I.getOperand().getParent();
954           if (DefMI->getOpcode() != X86::MOVPC32r)
955             return false;
956           assert(!isPICBase && "More than one PIC base?");
957           isPICBase = true;
958         }
959         return isPICBase;
960       } 
961       return false;
962     }
963  
964      case X86::LEA32r:
965      case X86::LEA64r: {
966        if (MI->getOperand(2).isImm() &&
967            MI->getOperand(3).isReg() && MI->getOperand(3).getReg() == 0 &&
968            !MI->getOperand(4).isReg()) {
969          // lea fi#, lea GV, etc. are all rematerializable.
970          if (!MI->getOperand(1).isReg())
971            return true;
972          unsigned BaseReg = MI->getOperand(1).getReg();
973          if (BaseReg == 0)
974            return true;
975          // Allow re-materialization of lea PICBase + x.
976          const MachineFunction &MF = *MI->getParent()->getParent();
977          const MachineRegisterInfo &MRI = MF.getRegInfo();
978          return regIsPICBase(BaseReg, MRI);
979        }
980        return false;
981      }
982   }
983
984   // All other instructions marked M_REMATERIALIZABLE are always trivially
985   // rematerializable.
986   return true;
987 }
988
989 /// isSafeToClobberEFLAGS - Return true if it's safe insert an instruction that
990 /// would clobber the EFLAGS condition register. Note the result may be
991 /// conservative. If it cannot definitely determine the safety after visiting
992 /// a few instructions in each direction it assumes it's not safe.
993 static bool isSafeToClobberEFLAGS(MachineBasicBlock &MBB,
994                                   MachineBasicBlock::iterator I) {
995   MachineBasicBlock::iterator E = MBB.end();
996
997   // It's always safe to clobber EFLAGS at the end of a block.
998   if (I == E)
999     return true;
1000
1001   // For compile time consideration, if we are not able to determine the
1002   // safety after visiting 4 instructions in each direction, we will assume
1003   // it's not safe.
1004   MachineBasicBlock::iterator Iter = I;
1005   for (unsigned i = 0; i < 4; ++i) {
1006     bool SeenDef = false;
1007     for (unsigned j = 0, e = Iter->getNumOperands(); j != e; ++j) {
1008       MachineOperand &MO = Iter->getOperand(j);
1009       if (!MO.isReg())
1010         continue;
1011       if (MO.getReg() == X86::EFLAGS) {
1012         if (MO.isUse())
1013           return false;
1014         SeenDef = true;
1015       }
1016     }
1017
1018     if (SeenDef)
1019       // This instruction defines EFLAGS, no need to look any further.
1020       return true;
1021     ++Iter;
1022     // Skip over DBG_VALUE.
1023     while (Iter != E && Iter->isDebugValue())
1024       ++Iter;
1025
1026     // If we make it to the end of the block, it's safe to clobber EFLAGS.
1027     if (Iter == E)
1028       return true;
1029   }
1030
1031   MachineBasicBlock::iterator B = MBB.begin();
1032   Iter = I;
1033   for (unsigned i = 0; i < 4; ++i) {
1034     // If we make it to the beginning of the block, it's safe to clobber
1035     // EFLAGS iff EFLAGS is not live-in.
1036     if (Iter == B)
1037       return !MBB.isLiveIn(X86::EFLAGS);
1038
1039     --Iter;
1040     // Skip over DBG_VALUE.
1041     while (Iter != B && Iter->isDebugValue())
1042       --Iter;
1043
1044     bool SawKill = false;
1045     for (unsigned j = 0, e = Iter->getNumOperands(); j != e; ++j) {
1046       MachineOperand &MO = Iter->getOperand(j);
1047       if (MO.isReg() && MO.getReg() == X86::EFLAGS) {
1048         if (MO.isDef()) return MO.isDead();
1049         if (MO.isKill()) SawKill = true;
1050       }
1051     }
1052
1053     if (SawKill)
1054       // This instruction kills EFLAGS and doesn't redefine it, so
1055       // there's no need to look further.
1056       return true;
1057   }
1058
1059   // Conservative answer.
1060   return false;
1061 }
1062
1063 void X86InstrInfo::reMaterialize(MachineBasicBlock &MBB,
1064                                  MachineBasicBlock::iterator I,
1065                                  unsigned DestReg, unsigned SubIdx,
1066                                  const MachineInstr *Orig,
1067                                  const TargetRegisterInfo &TRI) const {
1068   DebugLoc DL = Orig->getDebugLoc();
1069
1070   // MOV32r0 etc. are implemented with xor which clobbers condition code.
1071   // Re-materialize them as movri instructions to avoid side effects.
1072   bool Clone = true;
1073   unsigned Opc = Orig->getOpcode();
1074   switch (Opc) {
1075   default: break;
1076   case X86::MOV8r0:
1077   case X86::MOV16r0:
1078   case X86::MOV32r0:
1079   case X86::MOV64r0: {
1080     if (!isSafeToClobberEFLAGS(MBB, I)) {
1081       switch (Opc) {
1082       default: break;
1083       case X86::MOV8r0:  Opc = X86::MOV8ri;  break;
1084       case X86::MOV16r0: Opc = X86::MOV16ri; break;
1085       case X86::MOV32r0: Opc = X86::MOV32ri; break;
1086       case X86::MOV64r0: Opc = X86::MOV64ri64i32; break;
1087       }
1088       Clone = false;
1089     }
1090     break;
1091   }
1092   }
1093
1094   if (Clone) {
1095     MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
1096     MBB.insert(I, MI);
1097   } else {
1098     BuildMI(MBB, I, DL, get(Opc)).addOperand(Orig->getOperand(0)).addImm(0);
1099   }
1100
1101   MachineInstr *NewMI = prior(I);
1102   NewMI->substituteRegister(Orig->getOperand(0).getReg(), DestReg, SubIdx, TRI);
1103 }
1104
1105 /// hasLiveCondCodeDef - True if MI has a condition code def, e.g. EFLAGS, that
1106 /// is not marked dead.
1107 static bool hasLiveCondCodeDef(MachineInstr *MI) {
1108   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1109     MachineOperand &MO = MI->getOperand(i);
1110     if (MO.isReg() && MO.isDef() &&
1111         MO.getReg() == X86::EFLAGS && !MO.isDead()) {
1112       return true;
1113     }
1114   }
1115   return false;
1116 }
1117
1118 /// convertToThreeAddressWithLEA - Helper for convertToThreeAddress when
1119 /// 16-bit LEA is disabled, use 32-bit LEA to form 3-address code by promoting
1120 /// to a 32-bit superregister and then truncating back down to a 16-bit
1121 /// subregister.
1122 MachineInstr *
1123 X86InstrInfo::convertToThreeAddressWithLEA(unsigned MIOpc,
1124                                            MachineFunction::iterator &MFI,
1125                                            MachineBasicBlock::iterator &MBBI,
1126                                            LiveVariables *LV) const {
1127   MachineInstr *MI = MBBI;
1128   unsigned Dest = MI->getOperand(0).getReg();
1129   unsigned Src = MI->getOperand(1).getReg();
1130   bool isDead = MI->getOperand(0).isDead();
1131   bool isKill = MI->getOperand(1).isKill();
1132
1133   unsigned Opc = TM.getSubtarget<X86Subtarget>().is64Bit()
1134     ? X86::LEA64_32r : X86::LEA32r;
1135   MachineRegisterInfo &RegInfo = MFI->getParent()->getRegInfo();
1136   unsigned leaInReg = RegInfo.createVirtualRegister(&X86::GR32RegClass);
1137   unsigned leaOutReg = RegInfo.createVirtualRegister(&X86::GR32RegClass);
1138             
1139   // Build and insert into an implicit UNDEF value. This is OK because
1140   // well be shifting and then extracting the lower 16-bits. 
1141   // This has the potential to cause partial register stall. e.g.
1142   //   movw    (%rbp,%rcx,2), %dx
1143   //   leal    -65(%rdx), %esi
1144   // But testing has shown this *does* help performance in 64-bit mode (at
1145   // least on modern x86 machines).
1146   BuildMI(*MFI, MBBI, MI->getDebugLoc(), get(X86::IMPLICIT_DEF), leaInReg);
1147   MachineInstr *InsMI =
1148     BuildMI(*MFI, MBBI, MI->getDebugLoc(), get(TargetOpcode::COPY))
1149     .addReg(leaInReg, RegState::Define, X86::sub_16bit)
1150     .addReg(Src, getKillRegState(isKill));
1151
1152   MachineInstrBuilder MIB = BuildMI(*MFI, MBBI, MI->getDebugLoc(),
1153                                     get(Opc), leaOutReg);
1154   switch (MIOpc) {
1155   default:
1156     llvm_unreachable(0);
1157     break;
1158   case X86::SHL16ri: {
1159     unsigned ShAmt = MI->getOperand(2).getImm();
1160     MIB.addReg(0).addImm(1 << ShAmt)
1161        .addReg(leaInReg, RegState::Kill).addImm(0).addReg(0);
1162     break;
1163   }
1164   case X86::INC16r:
1165   case X86::INC64_16r:
1166     addRegOffset(MIB, leaInReg, true, 1);
1167     break;
1168   case X86::DEC16r:
1169   case X86::DEC64_16r:
1170     addRegOffset(MIB, leaInReg, true, -1);
1171     break;
1172   case X86::ADD16ri:
1173   case X86::ADD16ri8:
1174     addRegOffset(MIB, leaInReg, true, MI->getOperand(2).getImm());    
1175     break;
1176   case X86::ADD16rr: {
1177     unsigned Src2 = MI->getOperand(2).getReg();
1178     bool isKill2 = MI->getOperand(2).isKill();
1179     unsigned leaInReg2 = 0;
1180     MachineInstr *InsMI2 = 0;
1181     if (Src == Src2) {
1182       // ADD16rr %reg1028<kill>, %reg1028
1183       // just a single insert_subreg.
1184       addRegReg(MIB, leaInReg, true, leaInReg, false);
1185     } else {
1186       leaInReg2 = RegInfo.createVirtualRegister(&X86::GR32RegClass);
1187       // Build and insert into an implicit UNDEF value. This is OK because
1188       // well be shifting and then extracting the lower 16-bits. 
1189       BuildMI(*MFI, MIB, MI->getDebugLoc(), get(X86::IMPLICIT_DEF), leaInReg2);
1190       InsMI2 =
1191         BuildMI(*MFI, MIB, MI->getDebugLoc(), get(TargetOpcode::COPY))
1192         .addReg(leaInReg2, RegState::Define, X86::sub_16bit)
1193         .addReg(Src2, getKillRegState(isKill2));
1194       addRegReg(MIB, leaInReg, true, leaInReg2, true);
1195     }
1196     if (LV && isKill2 && InsMI2)
1197       LV->replaceKillInstruction(Src2, MI, InsMI2);
1198     break;
1199   }
1200   }
1201
1202   MachineInstr *NewMI = MIB;
1203   MachineInstr *ExtMI =
1204     BuildMI(*MFI, MBBI, MI->getDebugLoc(), get(TargetOpcode::COPY))
1205     .addReg(Dest, RegState::Define | getDeadRegState(isDead))
1206     .addReg(leaOutReg, RegState::Kill, X86::sub_16bit);
1207
1208   if (LV) {
1209     // Update live variables
1210     LV->getVarInfo(leaInReg).Kills.push_back(NewMI);
1211     LV->getVarInfo(leaOutReg).Kills.push_back(ExtMI);
1212     if (isKill)
1213       LV->replaceKillInstruction(Src, MI, InsMI);
1214     if (isDead)
1215       LV->replaceKillInstruction(Dest, MI, ExtMI);
1216   }
1217
1218   return ExtMI;
1219 }
1220
1221 /// convertToThreeAddress - This method must be implemented by targets that
1222 /// set the M_CONVERTIBLE_TO_3_ADDR flag.  When this flag is set, the target
1223 /// may be able to convert a two-address instruction into a true
1224 /// three-address instruction on demand.  This allows the X86 target (for
1225 /// example) to convert ADD and SHL instructions into LEA instructions if they
1226 /// would require register copies due to two-addressness.
1227 ///
1228 /// This method returns a null pointer if the transformation cannot be
1229 /// performed, otherwise it returns the new instruction.
1230 ///
1231 MachineInstr *
1232 X86InstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
1233                                     MachineBasicBlock::iterator &MBBI,
1234                                     LiveVariables *LV) const {
1235   MachineInstr *MI = MBBI;
1236   MachineFunction &MF = *MI->getParent()->getParent();
1237   // All instructions input are two-addr instructions.  Get the known operands.
1238   unsigned Dest = MI->getOperand(0).getReg();
1239   unsigned Src = MI->getOperand(1).getReg();
1240   bool isDead = MI->getOperand(0).isDead();
1241   bool isKill = MI->getOperand(1).isKill();
1242
1243   MachineInstr *NewMI = NULL;
1244   // FIXME: 16-bit LEA's are really slow on Athlons, but not bad on P4's.  When
1245   // we have better subtarget support, enable the 16-bit LEA generation here.
1246   // 16-bit LEA is also slow on Core2.
1247   bool DisableLEA16 = true;
1248   bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
1249
1250   unsigned MIOpc = MI->getOpcode();
1251   switch (MIOpc) {
1252   case X86::SHUFPSrri: {
1253     assert(MI->getNumOperands() == 4 && "Unknown shufps instruction!");
1254     if (!TM.getSubtarget<X86Subtarget>().hasSSE2()) return 0;
1255     
1256     unsigned B = MI->getOperand(1).getReg();
1257     unsigned C = MI->getOperand(2).getReg();
1258     if (B != C) return 0;
1259     unsigned A = MI->getOperand(0).getReg();
1260     unsigned M = MI->getOperand(3).getImm();
1261     NewMI = BuildMI(MF, MI->getDebugLoc(), get(X86::PSHUFDri))
1262       .addReg(A, RegState::Define | getDeadRegState(isDead))
1263       .addReg(B, getKillRegState(isKill)).addImm(M);
1264     break;
1265   }
1266   case X86::SHL64ri: {
1267     assert(MI->getNumOperands() >= 3 && "Unknown shift instruction!");
1268     // NOTE: LEA doesn't produce flags like shift does, but LLVM never uses
1269     // the flags produced by a shift yet, so this is safe.
1270     unsigned ShAmt = MI->getOperand(2).getImm();
1271     if (ShAmt == 0 || ShAmt >= 4) return 0;
1272
1273     NewMI = BuildMI(MF, MI->getDebugLoc(), get(X86::LEA64r))
1274       .addReg(Dest, RegState::Define | getDeadRegState(isDead))
1275       .addReg(0).addImm(1 << ShAmt)
1276       .addReg(Src, getKillRegState(isKill))
1277       .addImm(0).addReg(0);
1278     break;
1279   }
1280   case X86::SHL32ri: {
1281     assert(MI->getNumOperands() >= 3 && "Unknown shift instruction!");
1282     // NOTE: LEA doesn't produce flags like shift does, but LLVM never uses
1283     // the flags produced by a shift yet, so this is safe.
1284     unsigned ShAmt = MI->getOperand(2).getImm();
1285     if (ShAmt == 0 || ShAmt >= 4) return 0;
1286
1287     unsigned Opc = is64Bit ? X86::LEA64_32r : X86::LEA32r;
1288     NewMI = BuildMI(MF, MI->getDebugLoc(), get(Opc))
1289       .addReg(Dest, RegState::Define | getDeadRegState(isDead))
1290       .addReg(0).addImm(1 << ShAmt)
1291       .addReg(Src, getKillRegState(isKill)).addImm(0).addReg(0);
1292     break;
1293   }
1294   case X86::SHL16ri: {
1295     assert(MI->getNumOperands() >= 3 && "Unknown shift instruction!");
1296     // NOTE: LEA doesn't produce flags like shift does, but LLVM never uses
1297     // the flags produced by a shift yet, so this is safe.
1298     unsigned ShAmt = MI->getOperand(2).getImm();
1299     if (ShAmt == 0 || ShAmt >= 4) return 0;
1300
1301     if (DisableLEA16)
1302       return is64Bit ? convertToThreeAddressWithLEA(MIOpc, MFI, MBBI, LV) : 0;
1303     NewMI = BuildMI(MF, MI->getDebugLoc(), get(X86::LEA16r))
1304       .addReg(Dest, RegState::Define | getDeadRegState(isDead))
1305       .addReg(0).addImm(1 << ShAmt)
1306       .addReg(Src, getKillRegState(isKill))
1307       .addImm(0).addReg(0);
1308     break;
1309   }
1310   default: {
1311     // The following opcodes also sets the condition code register(s). Only
1312     // convert them to equivalent lea if the condition code register def's
1313     // are dead!
1314     if (hasLiveCondCodeDef(MI))
1315       return 0;
1316
1317     switch (MIOpc) {
1318     default: return 0;
1319     case X86::INC64r:
1320     case X86::INC32r:
1321     case X86::INC64_32r: {
1322       assert(MI->getNumOperands() >= 2 && "Unknown inc instruction!");
1323       unsigned Opc = MIOpc == X86::INC64r ? X86::LEA64r
1324         : (is64Bit ? X86::LEA64_32r : X86::LEA32r);
1325       NewMI = addRegOffset(BuildMI(MF, MI->getDebugLoc(), get(Opc))
1326                               .addReg(Dest, RegState::Define |
1327                                       getDeadRegState(isDead)),
1328                               Src, isKill, 1);
1329       break;
1330     }
1331     case X86::INC16r:
1332     case X86::INC64_16r:
1333       if (DisableLEA16)
1334         return is64Bit ? convertToThreeAddressWithLEA(MIOpc, MFI, MBBI, LV) : 0;
1335       assert(MI->getNumOperands() >= 2 && "Unknown inc instruction!");
1336       NewMI = addRegOffset(BuildMI(MF, MI->getDebugLoc(), get(X86::LEA16r))
1337                            .addReg(Dest, RegState::Define |
1338                                    getDeadRegState(isDead)),
1339                            Src, isKill, 1);
1340       break;
1341     case X86::DEC64r:
1342     case X86::DEC32r:
1343     case X86::DEC64_32r: {
1344       assert(MI->getNumOperands() >= 2 && "Unknown dec instruction!");
1345       unsigned Opc = MIOpc == X86::DEC64r ? X86::LEA64r
1346         : (is64Bit ? X86::LEA64_32r : X86::LEA32r);
1347       NewMI = addRegOffset(BuildMI(MF, MI->getDebugLoc(), get(Opc))
1348                               .addReg(Dest, RegState::Define |
1349                                       getDeadRegState(isDead)),
1350                               Src, isKill, -1);
1351       break;
1352     }
1353     case X86::DEC16r:
1354     case X86::DEC64_16r:
1355       if (DisableLEA16)
1356         return is64Bit ? convertToThreeAddressWithLEA(MIOpc, MFI, MBBI, LV) : 0;
1357       assert(MI->getNumOperands() >= 2 && "Unknown dec instruction!");
1358       NewMI = addRegOffset(BuildMI(MF, MI->getDebugLoc(), get(X86::LEA16r))
1359                            .addReg(Dest, RegState::Define |
1360                                    getDeadRegState(isDead)),
1361                            Src, isKill, -1);
1362       break;
1363     case X86::ADD64rr:
1364     case X86::ADD32rr: {
1365       assert(MI->getNumOperands() >= 3 && "Unknown add instruction!");
1366       unsigned Opc = MIOpc == X86::ADD64rr ? X86::LEA64r
1367         : (is64Bit ? X86::LEA64_32r : X86::LEA32r);
1368       unsigned Src2 = MI->getOperand(2).getReg();
1369       bool isKill2 = MI->getOperand(2).isKill();
1370       NewMI = addRegReg(BuildMI(MF, MI->getDebugLoc(), get(Opc))
1371                         .addReg(Dest, RegState::Define |
1372                                 getDeadRegState(isDead)),
1373                         Src, isKill, Src2, isKill2);
1374       if (LV && isKill2)
1375         LV->replaceKillInstruction(Src2, MI, NewMI);
1376       break;
1377     }
1378     case X86::ADD16rr: {
1379       if (DisableLEA16)
1380         return is64Bit ? convertToThreeAddressWithLEA(MIOpc, MFI, MBBI, LV) : 0;
1381       assert(MI->getNumOperands() >= 3 && "Unknown add instruction!");
1382       unsigned Src2 = MI->getOperand(2).getReg();
1383       bool isKill2 = MI->getOperand(2).isKill();
1384       NewMI = addRegReg(BuildMI(MF, MI->getDebugLoc(), get(X86::LEA16r))
1385                         .addReg(Dest, RegState::Define |
1386                                 getDeadRegState(isDead)),
1387                         Src, isKill, Src2, isKill2);
1388       if (LV && isKill2)
1389         LV->replaceKillInstruction(Src2, MI, NewMI);
1390       break;
1391     }
1392     case X86::ADD64ri32:
1393     case X86::ADD64ri8:
1394       assert(MI->getNumOperands() >= 3 && "Unknown add instruction!");
1395       NewMI = addRegOffset(BuildMI(MF, MI->getDebugLoc(), get(X86::LEA64r))
1396                               .addReg(Dest, RegState::Define |
1397                                       getDeadRegState(isDead)),
1398                               Src, isKill, MI->getOperand(2).getImm());
1399       break;
1400     case X86::ADD32ri:
1401     case X86::ADD32ri8: {
1402       assert(MI->getNumOperands() >= 3 && "Unknown add instruction!");
1403       unsigned Opc = is64Bit ? X86::LEA64_32r : X86::LEA32r;
1404       NewMI = addRegOffset(BuildMI(MF, MI->getDebugLoc(), get(Opc))
1405                               .addReg(Dest, RegState::Define |
1406                                       getDeadRegState(isDead)),
1407                                 Src, isKill, MI->getOperand(2).getImm());
1408       break;
1409     }
1410     case X86::ADD16ri:
1411     case X86::ADD16ri8:
1412       if (DisableLEA16)
1413         return is64Bit ? convertToThreeAddressWithLEA(MIOpc, MFI, MBBI, LV) : 0;
1414       assert(MI->getNumOperands() >= 3 && "Unknown add instruction!");
1415       NewMI = addRegOffset(BuildMI(MF, MI->getDebugLoc(), get(X86::LEA16r))
1416                               .addReg(Dest, RegState::Define |
1417                                       getDeadRegState(isDead)),
1418                               Src, isKill, MI->getOperand(2).getImm());
1419       break;
1420     }
1421   }
1422   }
1423
1424   if (!NewMI) return 0;
1425
1426   if (LV) {  // Update live variables
1427     if (isKill)
1428       LV->replaceKillInstruction(Src, MI, NewMI);
1429     if (isDead)
1430       LV->replaceKillInstruction(Dest, MI, NewMI);
1431   }
1432
1433   MFI->insert(MBBI, NewMI);          // Insert the new inst    
1434   return NewMI;
1435 }
1436
1437 /// commuteInstruction - We have a few instructions that must be hacked on to
1438 /// commute them.
1439 ///
1440 MachineInstr *
1441 X86InstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
1442   switch (MI->getOpcode()) {
1443   case X86::SHRD16rri8: // A = SHRD16rri8 B, C, I -> A = SHLD16rri8 C, B, (16-I)
1444   case X86::SHLD16rri8: // A = SHLD16rri8 B, C, I -> A = SHRD16rri8 C, B, (16-I)
1445   case X86::SHRD32rri8: // A = SHRD32rri8 B, C, I -> A = SHLD32rri8 C, B, (32-I)
1446   case X86::SHLD32rri8: // A = SHLD32rri8 B, C, I -> A = SHRD32rri8 C, B, (32-I)
1447   case X86::SHRD64rri8: // A = SHRD64rri8 B, C, I -> A = SHLD64rri8 C, B, (64-I)
1448   case X86::SHLD64rri8:{// A = SHLD64rri8 B, C, I -> A = SHRD64rri8 C, B, (64-I)
1449     unsigned Opc;
1450     unsigned Size;
1451     switch (MI->getOpcode()) {
1452     default: llvm_unreachable("Unreachable!");
1453     case X86::SHRD16rri8: Size = 16; Opc = X86::SHLD16rri8; break;
1454     case X86::SHLD16rri8: Size = 16; Opc = X86::SHRD16rri8; break;
1455     case X86::SHRD32rri8: Size = 32; Opc = X86::SHLD32rri8; break;
1456     case X86::SHLD32rri8: Size = 32; Opc = X86::SHRD32rri8; break;
1457     case X86::SHRD64rri8: Size = 64; Opc = X86::SHLD64rri8; break;
1458     case X86::SHLD64rri8: Size = 64; Opc = X86::SHRD64rri8; break;
1459     }
1460     unsigned Amt = MI->getOperand(3).getImm();
1461     if (NewMI) {
1462       MachineFunction &MF = *MI->getParent()->getParent();
1463       MI = MF.CloneMachineInstr(MI);
1464       NewMI = false;
1465     }
1466     MI->setDesc(get(Opc));
1467     MI->getOperand(3).setImm(Size-Amt);
1468     return TargetInstrInfoImpl::commuteInstruction(MI, NewMI);
1469   }
1470   case X86::CMOVB16rr:
1471   case X86::CMOVB32rr:
1472   case X86::CMOVB64rr:
1473   case X86::CMOVAE16rr:
1474   case X86::CMOVAE32rr:
1475   case X86::CMOVAE64rr:
1476   case X86::CMOVE16rr:
1477   case X86::CMOVE32rr:
1478   case X86::CMOVE64rr:
1479   case X86::CMOVNE16rr:
1480   case X86::CMOVNE32rr:
1481   case X86::CMOVNE64rr:
1482   case X86::CMOVBE16rr:
1483   case X86::CMOVBE32rr:
1484   case X86::CMOVBE64rr:
1485   case X86::CMOVA16rr:
1486   case X86::CMOVA32rr:
1487   case X86::CMOVA64rr:
1488   case X86::CMOVL16rr:
1489   case X86::CMOVL32rr:
1490   case X86::CMOVL64rr:
1491   case X86::CMOVGE16rr:
1492   case X86::CMOVGE32rr:
1493   case X86::CMOVGE64rr:
1494   case X86::CMOVLE16rr:
1495   case X86::CMOVLE32rr:
1496   case X86::CMOVLE64rr:
1497   case X86::CMOVG16rr:
1498   case X86::CMOVG32rr:
1499   case X86::CMOVG64rr:
1500   case X86::CMOVS16rr:
1501   case X86::CMOVS32rr:
1502   case X86::CMOVS64rr:
1503   case X86::CMOVNS16rr:
1504   case X86::CMOVNS32rr:
1505   case X86::CMOVNS64rr:
1506   case X86::CMOVP16rr:
1507   case X86::CMOVP32rr:
1508   case X86::CMOVP64rr:
1509   case X86::CMOVNP16rr:
1510   case X86::CMOVNP32rr:
1511   case X86::CMOVNP64rr:
1512   case X86::CMOVO16rr:
1513   case X86::CMOVO32rr:
1514   case X86::CMOVO64rr:
1515   case X86::CMOVNO16rr:
1516   case X86::CMOVNO32rr:
1517   case X86::CMOVNO64rr: {
1518     unsigned Opc = 0;
1519     switch (MI->getOpcode()) {
1520     default: break;
1521     case X86::CMOVB16rr:  Opc = X86::CMOVAE16rr; break;
1522     case X86::CMOVB32rr:  Opc = X86::CMOVAE32rr; break;
1523     case X86::CMOVB64rr:  Opc = X86::CMOVAE64rr; break;
1524     case X86::CMOVAE16rr: Opc = X86::CMOVB16rr; break;
1525     case X86::CMOVAE32rr: Opc = X86::CMOVB32rr; break;
1526     case X86::CMOVAE64rr: Opc = X86::CMOVB64rr; break;
1527     case X86::CMOVE16rr:  Opc = X86::CMOVNE16rr; break;
1528     case X86::CMOVE32rr:  Opc = X86::CMOVNE32rr; break;
1529     case X86::CMOVE64rr:  Opc = X86::CMOVNE64rr; break;
1530     case X86::CMOVNE16rr: Opc = X86::CMOVE16rr; break;
1531     case X86::CMOVNE32rr: Opc = X86::CMOVE32rr; break;
1532     case X86::CMOVNE64rr: Opc = X86::CMOVE64rr; break;
1533     case X86::CMOVBE16rr: Opc = X86::CMOVA16rr; break;
1534     case X86::CMOVBE32rr: Opc = X86::CMOVA32rr; break;
1535     case X86::CMOVBE64rr: Opc = X86::CMOVA64rr; break;
1536     case X86::CMOVA16rr:  Opc = X86::CMOVBE16rr; break;
1537     case X86::CMOVA32rr:  Opc = X86::CMOVBE32rr; break;
1538     case X86::CMOVA64rr:  Opc = X86::CMOVBE64rr; break;
1539     case X86::CMOVL16rr:  Opc = X86::CMOVGE16rr; break;
1540     case X86::CMOVL32rr:  Opc = X86::CMOVGE32rr; break;
1541     case X86::CMOVL64rr:  Opc = X86::CMOVGE64rr; break;
1542     case X86::CMOVGE16rr: Opc = X86::CMOVL16rr; break;
1543     case X86::CMOVGE32rr: Opc = X86::CMOVL32rr; break;
1544     case X86::CMOVGE64rr: Opc = X86::CMOVL64rr; break;
1545     case X86::CMOVLE16rr: Opc = X86::CMOVG16rr; break;
1546     case X86::CMOVLE32rr: Opc = X86::CMOVG32rr; break;
1547     case X86::CMOVLE64rr: Opc = X86::CMOVG64rr; break;
1548     case X86::CMOVG16rr:  Opc = X86::CMOVLE16rr; break;
1549     case X86::CMOVG32rr:  Opc = X86::CMOVLE32rr; break;
1550     case X86::CMOVG64rr:  Opc = X86::CMOVLE64rr; break;
1551     case X86::CMOVS16rr:  Opc = X86::CMOVNS16rr; break;
1552     case X86::CMOVS32rr:  Opc = X86::CMOVNS32rr; break;
1553     case X86::CMOVS64rr:  Opc = X86::CMOVNS64rr; break;
1554     case X86::CMOVNS16rr: Opc = X86::CMOVS16rr; break;
1555     case X86::CMOVNS32rr: Opc = X86::CMOVS32rr; break;
1556     case X86::CMOVNS64rr: Opc = X86::CMOVS64rr; break;
1557     case X86::CMOVP16rr:  Opc = X86::CMOVNP16rr; break;
1558     case X86::CMOVP32rr:  Opc = X86::CMOVNP32rr; break;
1559     case X86::CMOVP64rr:  Opc = X86::CMOVNP64rr; break;
1560     case X86::CMOVNP16rr: Opc = X86::CMOVP16rr; break;
1561     case X86::CMOVNP32rr: Opc = X86::CMOVP32rr; break;
1562     case X86::CMOVNP64rr: Opc = X86::CMOVP64rr; break;
1563     case X86::CMOVO16rr:  Opc = X86::CMOVNO16rr; break;
1564     case X86::CMOVO32rr:  Opc = X86::CMOVNO32rr; break;
1565     case X86::CMOVO64rr:  Opc = X86::CMOVNO64rr; break;
1566     case X86::CMOVNO16rr: Opc = X86::CMOVO16rr; break;
1567     case X86::CMOVNO32rr: Opc = X86::CMOVO32rr; break;
1568     case X86::CMOVNO64rr: Opc = X86::CMOVO64rr; break;
1569     }
1570     if (NewMI) {
1571       MachineFunction &MF = *MI->getParent()->getParent();
1572       MI = MF.CloneMachineInstr(MI);
1573       NewMI = false;
1574     }
1575     MI->setDesc(get(Opc));
1576     // Fallthrough intended.
1577   }
1578   default:
1579     return TargetInstrInfoImpl::commuteInstruction(MI, NewMI);
1580   }
1581 }
1582
1583 static X86::CondCode GetCondFromBranchOpc(unsigned BrOpc) {
1584   switch (BrOpc) {
1585   default: return X86::COND_INVALID;
1586   case X86::JE_4:  return X86::COND_E;
1587   case X86::JNE_4: return X86::COND_NE;
1588   case X86::JL_4:  return X86::COND_L;
1589   case X86::JLE_4: return X86::COND_LE;
1590   case X86::JG_4:  return X86::COND_G;
1591   case X86::JGE_4: return X86::COND_GE;
1592   case X86::JB_4:  return X86::COND_B;
1593   case X86::JBE_4: return X86::COND_BE;
1594   case X86::JA_4:  return X86::COND_A;
1595   case X86::JAE_4: return X86::COND_AE;
1596   case X86::JS_4:  return X86::COND_S;
1597   case X86::JNS_4: return X86::COND_NS;
1598   case X86::JP_4:  return X86::COND_P;
1599   case X86::JNP_4: return X86::COND_NP;
1600   case X86::JO_4:  return X86::COND_O;
1601   case X86::JNO_4: return X86::COND_NO;
1602   }
1603 }
1604
1605 unsigned X86::GetCondBranchFromCond(X86::CondCode CC) {
1606   switch (CC) {
1607   default: llvm_unreachable("Illegal condition code!");
1608   case X86::COND_E:  return X86::JE_4;
1609   case X86::COND_NE: return X86::JNE_4;
1610   case X86::COND_L:  return X86::JL_4;
1611   case X86::COND_LE: return X86::JLE_4;
1612   case X86::COND_G:  return X86::JG_4;
1613   case X86::COND_GE: return X86::JGE_4;
1614   case X86::COND_B:  return X86::JB_4;
1615   case X86::COND_BE: return X86::JBE_4;
1616   case X86::COND_A:  return X86::JA_4;
1617   case X86::COND_AE: return X86::JAE_4;
1618   case X86::COND_S:  return X86::JS_4;
1619   case X86::COND_NS: return X86::JNS_4;
1620   case X86::COND_P:  return X86::JP_4;
1621   case X86::COND_NP: return X86::JNP_4;
1622   case X86::COND_O:  return X86::JO_4;
1623   case X86::COND_NO: return X86::JNO_4;
1624   }
1625 }
1626
1627 /// GetOppositeBranchCondition - Return the inverse of the specified condition,
1628 /// e.g. turning COND_E to COND_NE.
1629 X86::CondCode X86::GetOppositeBranchCondition(X86::CondCode CC) {
1630   switch (CC) {
1631   default: llvm_unreachable("Illegal condition code!");
1632   case X86::COND_E:  return X86::COND_NE;
1633   case X86::COND_NE: return X86::COND_E;
1634   case X86::COND_L:  return X86::COND_GE;
1635   case X86::COND_LE: return X86::COND_G;
1636   case X86::COND_G:  return X86::COND_LE;
1637   case X86::COND_GE: return X86::COND_L;
1638   case X86::COND_B:  return X86::COND_AE;
1639   case X86::COND_BE: return X86::COND_A;
1640   case X86::COND_A:  return X86::COND_BE;
1641   case X86::COND_AE: return X86::COND_B;
1642   case X86::COND_S:  return X86::COND_NS;
1643   case X86::COND_NS: return X86::COND_S;
1644   case X86::COND_P:  return X86::COND_NP;
1645   case X86::COND_NP: return X86::COND_P;
1646   case X86::COND_O:  return X86::COND_NO;
1647   case X86::COND_NO: return X86::COND_O;
1648   }
1649 }
1650
1651 bool X86InstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
1652   const TargetInstrDesc &TID = MI->getDesc();
1653   if (!TID.isTerminator()) return false;
1654   
1655   // Conditional branch is a special case.
1656   if (TID.isBranch() && !TID.isBarrier())
1657     return true;
1658   if (!TID.isPredicable())
1659     return true;
1660   return !isPredicated(MI);
1661 }
1662
1663 // For purposes of branch analysis do not count FP_REG_KILL as a terminator.
1664 static bool isBrAnalysisUnpredicatedTerminator(const MachineInstr *MI,
1665                                                const X86InstrInfo &TII) {
1666   if (MI->getOpcode() == X86::FP_REG_KILL)
1667     return false;
1668   return TII.isUnpredicatedTerminator(MI);
1669 }
1670
1671 bool X86InstrInfo::AnalyzeBranch(MachineBasicBlock &MBB, 
1672                                  MachineBasicBlock *&TBB,
1673                                  MachineBasicBlock *&FBB,
1674                                  SmallVectorImpl<MachineOperand> &Cond,
1675                                  bool AllowModify) const {
1676   // Start from the bottom of the block and work up, examining the
1677   // terminator instructions.
1678   MachineBasicBlock::iterator I = MBB.end();
1679   MachineBasicBlock::iterator UnCondBrIter = MBB.end();
1680   while (I != MBB.begin()) {
1681     --I;
1682     if (I->isDebugValue())
1683       continue;
1684
1685     // Working from the bottom, when we see a non-terminator instruction, we're
1686     // done.
1687     if (!isBrAnalysisUnpredicatedTerminator(I, *this))
1688       break;
1689
1690     // A terminator that isn't a branch can't easily be handled by this
1691     // analysis.
1692     if (!I->getDesc().isBranch())
1693       return true;
1694
1695     // Handle unconditional branches.
1696     if (I->getOpcode() == X86::JMP_4) {
1697       UnCondBrIter = I;
1698
1699       if (!AllowModify) {
1700         TBB = I->getOperand(0).getMBB();
1701         continue;
1702       }
1703
1704       // If the block has any instructions after a JMP, delete them.
1705       while (llvm::next(I) != MBB.end())
1706         llvm::next(I)->eraseFromParent();
1707
1708       Cond.clear();
1709       FBB = 0;
1710
1711       // Delete the JMP if it's equivalent to a fall-through.
1712       if (MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) {
1713         TBB = 0;
1714         I->eraseFromParent();
1715         I = MBB.end();
1716         UnCondBrIter = MBB.end();
1717         continue;
1718       }
1719
1720       // TBB is used to indicate the unconditional destination.
1721       TBB = I->getOperand(0).getMBB();
1722       continue;
1723     }
1724
1725     // Handle conditional branches.
1726     X86::CondCode BranchCode = GetCondFromBranchOpc(I->getOpcode());
1727     if (BranchCode == X86::COND_INVALID)
1728       return true;  // Can't handle indirect branch.
1729
1730     // Working from the bottom, handle the first conditional branch.
1731     if (Cond.empty()) {
1732       MachineBasicBlock *TargetBB = I->getOperand(0).getMBB();
1733       if (AllowModify && UnCondBrIter != MBB.end() &&
1734           MBB.isLayoutSuccessor(TargetBB)) {
1735         // If we can modify the code and it ends in something like:
1736         //
1737         //     jCC L1
1738         //     jmp L2
1739         //   L1:
1740         //     ...
1741         //   L2:
1742         //
1743         // Then we can change this to:
1744         //
1745         //     jnCC L2
1746         //   L1:
1747         //     ...
1748         //   L2:
1749         //
1750         // Which is a bit more efficient.
1751         // We conditionally jump to the fall-through block.
1752         BranchCode = GetOppositeBranchCondition(BranchCode);
1753         unsigned JNCC = GetCondBranchFromCond(BranchCode);
1754         MachineBasicBlock::iterator OldInst = I;
1755
1756         BuildMI(MBB, UnCondBrIter, MBB.findDebugLoc(I), get(JNCC))
1757           .addMBB(UnCondBrIter->getOperand(0).getMBB());
1758         BuildMI(MBB, UnCondBrIter, MBB.findDebugLoc(I), get(X86::JMP_4))
1759           .addMBB(TargetBB);
1760         MBB.addSuccessor(TargetBB);
1761
1762         OldInst->eraseFromParent();
1763         UnCondBrIter->eraseFromParent();
1764
1765         // Restart the analysis.
1766         UnCondBrIter = MBB.end();
1767         I = MBB.end();
1768         continue;
1769       }
1770
1771       FBB = TBB;
1772       TBB = I->getOperand(0).getMBB();
1773       Cond.push_back(MachineOperand::CreateImm(BranchCode));
1774       continue;
1775     }
1776
1777     // Handle subsequent conditional branches. Only handle the case where all
1778     // conditional branches branch to the same destination and their condition
1779     // opcodes fit one of the special multi-branch idioms.
1780     assert(Cond.size() == 1);
1781     assert(TBB);
1782
1783     // Only handle the case where all conditional branches branch to the same
1784     // destination.
1785     if (TBB != I->getOperand(0).getMBB())
1786       return true;
1787
1788     // If the conditions are the same, we can leave them alone.
1789     X86::CondCode OldBranchCode = (X86::CondCode)Cond[0].getImm();
1790     if (OldBranchCode == BranchCode)
1791       continue;
1792
1793     // If they differ, see if they fit one of the known patterns. Theoretically,
1794     // we could handle more patterns here, but we shouldn't expect to see them
1795     // if instruction selection has done a reasonable job.
1796     if ((OldBranchCode == X86::COND_NP &&
1797          BranchCode == X86::COND_E) ||
1798         (OldBranchCode == X86::COND_E &&
1799          BranchCode == X86::COND_NP))
1800       BranchCode = X86::COND_NP_OR_E;
1801     else if ((OldBranchCode == X86::COND_P &&
1802               BranchCode == X86::COND_NE) ||
1803              (OldBranchCode == X86::COND_NE &&
1804               BranchCode == X86::COND_P))
1805       BranchCode = X86::COND_NE_OR_P;
1806     else
1807       return true;
1808
1809     // Update the MachineOperand.
1810     Cond[0].setImm(BranchCode);
1811   }
1812
1813   return false;
1814 }
1815
1816 unsigned X86InstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
1817   MachineBasicBlock::iterator I = MBB.end();
1818   unsigned Count = 0;
1819
1820   while (I != MBB.begin()) {
1821     --I;
1822     if (I->isDebugValue())
1823       continue;
1824     if (I->getOpcode() != X86::JMP_4 &&
1825         GetCondFromBranchOpc(I->getOpcode()) == X86::COND_INVALID)
1826       break;
1827     // Remove the branch.
1828     I->eraseFromParent();
1829     I = MBB.end();
1830     ++Count;
1831   }
1832   
1833   return Count;
1834 }
1835
1836 unsigned
1837 X86InstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
1838                            MachineBasicBlock *FBB,
1839                            const SmallVectorImpl<MachineOperand> &Cond,
1840                            DebugLoc DL) const {
1841   // Shouldn't be a fall through.
1842   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
1843   assert((Cond.size() == 1 || Cond.size() == 0) &&
1844          "X86 branch conditions have one component!");
1845
1846   if (Cond.empty()) {
1847     // Unconditional branch?
1848     assert(!FBB && "Unconditional branch with multiple successors!");
1849     BuildMI(&MBB, DL, get(X86::JMP_4)).addMBB(TBB);
1850     return 1;
1851   }
1852
1853   // Conditional branch.
1854   unsigned Count = 0;
1855   X86::CondCode CC = (X86::CondCode)Cond[0].getImm();
1856   switch (CC) {
1857   case X86::COND_NP_OR_E:
1858     // Synthesize NP_OR_E with two branches.
1859     BuildMI(&MBB, DL, get(X86::JNP_4)).addMBB(TBB);
1860     ++Count;
1861     BuildMI(&MBB, DL, get(X86::JE_4)).addMBB(TBB);
1862     ++Count;
1863     break;
1864   case X86::COND_NE_OR_P:
1865     // Synthesize NE_OR_P with two branches.
1866     BuildMI(&MBB, DL, get(X86::JNE_4)).addMBB(TBB);
1867     ++Count;
1868     BuildMI(&MBB, DL, get(X86::JP_4)).addMBB(TBB);
1869     ++Count;
1870     break;
1871   default: {
1872     unsigned Opc = GetCondBranchFromCond(CC);
1873     BuildMI(&MBB, DL, get(Opc)).addMBB(TBB);
1874     ++Count;
1875   }
1876   }
1877   if (FBB) {
1878     // Two-way Conditional branch. Insert the second branch.
1879     BuildMI(&MBB, DL, get(X86::JMP_4)).addMBB(FBB);
1880     ++Count;
1881   }
1882   return Count;
1883 }
1884
1885 /// isHReg - Test if the given register is a physical h register.
1886 static bool isHReg(unsigned Reg) {
1887   return X86::GR8_ABCD_HRegClass.contains(Reg);
1888 }
1889
1890 bool X86InstrInfo::copyRegToReg(MachineBasicBlock &MBB,
1891                                 MachineBasicBlock::iterator MI,
1892                                 unsigned DestReg, unsigned SrcReg,
1893                                 const TargetRegisterClass *DestRC,
1894                                 const TargetRegisterClass *SrcRC,
1895                                 DebugLoc DL) const {
1896
1897   // Determine if DstRC and SrcRC have a common superclass in common.
1898   const TargetRegisterClass *CommonRC = DestRC;
1899   if (DestRC == SrcRC)
1900     /* Source and destination have the same register class. */;
1901   else if (CommonRC->hasSuperClass(SrcRC))
1902     CommonRC = SrcRC;
1903   else if (!DestRC->hasSubClass(SrcRC)) {
1904     // Neither of GR64_NOREX or GR64_NOSP is a superclass of the other,
1905     // but we want to copy them as GR64. Similarly, for GR32_NOREX and
1906     // GR32_NOSP, copy as GR32.
1907     if (SrcRC->hasSuperClass(&X86::GR64RegClass) &&
1908         DestRC->hasSuperClass(&X86::GR64RegClass))
1909       CommonRC = &X86::GR64RegClass;
1910     else if (SrcRC->hasSuperClass(&X86::GR32RegClass) &&
1911              DestRC->hasSuperClass(&X86::GR32RegClass))
1912       CommonRC = &X86::GR32RegClass;
1913     else if (SrcRC->hasSuperClass(&X86::GR8RegClass) &&
1914              DestRC->hasSuperClass(&X86::GR8RegClass))
1915       CommonRC = &X86::GR8RegClass;
1916     else
1917       CommonRC = 0;
1918   }
1919
1920   if (CommonRC) {
1921     unsigned Opc;
1922     if (CommonRC == &X86::GR64RegClass || CommonRC == &X86::GR64_NOSPRegClass) {
1923       Opc = X86::MOV64rr;
1924     } else if (CommonRC == &X86::GR32RegClass ||
1925                CommonRC == &X86::GR32_NOSPRegClass) {
1926       Opc = X86::MOV32rr;
1927     } else if (CommonRC == &X86::GR16RegClass) {
1928       Opc = X86::MOV16rr;
1929     } else if (CommonRC == &X86::GR8RegClass) {
1930       // Copying to or from a physical H register on x86-64 requires a NOREX
1931       // move.  Otherwise use a normal move.
1932       if ((isHReg(DestReg) || isHReg(SrcReg) ||
1933            SrcRC == &X86::GR8_ABCD_HRegClass ||
1934            DestRC == &X86::GR8_ABCD_HRegClass) &&
1935           TM.getSubtarget<X86Subtarget>().is64Bit())
1936         Opc = X86::MOV8rr_NOREX;
1937       else
1938         Opc = X86::MOV8rr;
1939     } else if (CommonRC == &X86::GR64_ABCDRegClass) {
1940       Opc = X86::MOV64rr;
1941     } else if (CommonRC == &X86::GR32_ABCDRegClass) {
1942       Opc = X86::MOV32rr;
1943     } else if (CommonRC == &X86::GR16_ABCDRegClass) {
1944       Opc = X86::MOV16rr;
1945     } else if (CommonRC == &X86::GR8_ABCD_LRegClass) {
1946       Opc = X86::MOV8rr;
1947     } else if (CommonRC == &X86::GR8_ABCD_HRegClass) {
1948       if (TM.getSubtarget<X86Subtarget>().is64Bit())
1949         Opc = X86::MOV8rr_NOREX;
1950       else
1951         Opc = X86::MOV8rr;
1952     } else if (CommonRC == &X86::GR64_NOREXRegClass ||
1953                CommonRC == &X86::GR64_NOREX_NOSPRegClass) {
1954       Opc = X86::MOV64rr;
1955     } else if (CommonRC == &X86::GR32_NOREXRegClass) {
1956       Opc = X86::MOV32rr;
1957     } else if (CommonRC == &X86::GR16_NOREXRegClass) {
1958       Opc = X86::MOV16rr;
1959     } else if (CommonRC == &X86::GR8_NOREXRegClass) {
1960       Opc = X86::MOV8rr;
1961     } else if (CommonRC == &X86::GR64_TCRegClass) {
1962       Opc = X86::MOV64rr_TC;
1963     } else if (CommonRC == &X86::GR32_TCRegClass) {
1964       Opc = X86::MOV32rr_TC;
1965     } else if (CommonRC == &X86::RFP32RegClass) {
1966       Opc = X86::MOV_Fp3232;
1967     } else if (CommonRC == &X86::RFP64RegClass || CommonRC == &X86::RSTRegClass) {
1968       Opc = X86::MOV_Fp6464;
1969     } else if (CommonRC == &X86::RFP80RegClass) {
1970       Opc = X86::MOV_Fp8080;
1971     } else if (CommonRC == &X86::FR32RegClass) {
1972       Opc = X86::FsMOVAPSrr;
1973     } else if (CommonRC == &X86::FR64RegClass) {
1974       Opc = X86::FsMOVAPDrr;
1975     } else if (CommonRC == &X86::VR128RegClass) {
1976       Opc = X86::MOVAPSrr;
1977     } else if (CommonRC == &X86::VR64RegClass) {
1978       Opc = X86::MMX_MOVQ64rr;
1979     } else {
1980       return false;
1981     }
1982     BuildMI(MBB, MI, DL, get(Opc), DestReg).addReg(SrcReg);
1983     return true;
1984   }
1985
1986   // Moving EFLAGS to / from another register requires a push and a pop.
1987   if (SrcRC == &X86::CCRRegClass) {
1988     if (SrcReg != X86::EFLAGS)
1989       return false;
1990     if (DestRC == &X86::GR64RegClass || DestRC == &X86::GR64_NOSPRegClass) {
1991       BuildMI(MBB, MI, DL, get(X86::PUSHF64));
1992       BuildMI(MBB, MI, DL, get(X86::POP64r), DestReg);
1993       return true;
1994     } else if (DestRC == &X86::GR32RegClass ||
1995                DestRC == &X86::GR32_NOSPRegClass) {
1996       BuildMI(MBB, MI, DL, get(X86::PUSHF32));
1997       BuildMI(MBB, MI, DL, get(X86::POP32r), DestReg);
1998       return true;
1999     }
2000   } else if (DestRC == &X86::CCRRegClass) {
2001     if (DestReg != X86::EFLAGS)
2002       return false;
2003     if (SrcRC == &X86::GR64RegClass || DestRC == &X86::GR64_NOSPRegClass) {
2004       BuildMI(MBB, MI, DL, get(X86::PUSH64r)).addReg(SrcReg);
2005       BuildMI(MBB, MI, DL, get(X86::POPF64));
2006       return true;
2007     } else if (SrcRC == &X86::GR32RegClass ||
2008                DestRC == &X86::GR32_NOSPRegClass) {
2009       BuildMI(MBB, MI, DL, get(X86::PUSH32r)).addReg(SrcReg);
2010       BuildMI(MBB, MI, DL, get(X86::POPF32));
2011       return true;
2012     }
2013   }
2014
2015   // Moving from ST(0) turns into FpGET_ST0_32 etc.
2016   if (SrcRC == &X86::RSTRegClass) {
2017     // Copying from ST(0)/ST(1).
2018     if (SrcReg != X86::ST0 && SrcReg != X86::ST1)
2019       // Can only copy from ST(0)/ST(1) right now
2020       return false;
2021     bool isST0 = SrcReg == X86::ST0;
2022     unsigned Opc;
2023     if (DestRC == &X86::RFP32RegClass)
2024       Opc = isST0 ? X86::FpGET_ST0_32 : X86::FpGET_ST1_32;
2025     else if (DestRC == &X86::RFP64RegClass)
2026       Opc = isST0 ? X86::FpGET_ST0_64 : X86::FpGET_ST1_64;
2027     else {
2028       if (DestRC != &X86::RFP80RegClass)
2029         return false;
2030       Opc = isST0 ? X86::FpGET_ST0_80 : X86::FpGET_ST1_80;
2031     }
2032     BuildMI(MBB, MI, DL, get(Opc), DestReg);
2033     return true;
2034   }
2035
2036   // Moving to ST(0) turns into FpSET_ST0_32 etc.
2037   if (DestRC == &X86::RSTRegClass) {
2038     // Copying to ST(0) / ST(1).
2039     if (DestReg != X86::ST0 && DestReg != X86::ST1)
2040       // Can only copy to TOS right now
2041       return false;
2042     bool isST0 = DestReg == X86::ST0;
2043     unsigned Opc;
2044     if (SrcRC == &X86::RFP32RegClass)
2045       Opc = isST0 ? X86::FpSET_ST0_32 : X86::FpSET_ST1_32;
2046     else if (SrcRC == &X86::RFP64RegClass)
2047       Opc = isST0 ? X86::FpSET_ST0_64 : X86::FpSET_ST1_64;
2048     else {
2049       if (SrcRC != &X86::RFP80RegClass)
2050         return false;
2051       Opc = isST0 ? X86::FpSET_ST0_80 : X86::FpSET_ST1_80;
2052     }
2053     BuildMI(MBB, MI, DL, get(Opc)).addReg(SrcReg);
2054     return true;
2055   }
2056   
2057   // Not yet supported!
2058   return false;
2059 }
2060
2061 void X86InstrInfo::copyPhysReg(MachineBasicBlock &MBB,
2062                                MachineBasicBlock::iterator MI, DebugLoc DL,
2063                                unsigned DestReg, unsigned SrcReg,
2064                                bool KillSrc) const {
2065   // First deal with the normal symmetric copies.
2066   unsigned Opc = 0;
2067   if (X86::GR64RegClass.contains(DestReg, SrcReg))
2068     Opc = X86::MOV64rr;
2069   else if (X86::GR32RegClass.contains(DestReg, SrcReg))
2070     Opc = X86::MOV32rr;
2071   else if (X86::GR16RegClass.contains(DestReg, SrcReg))
2072     Opc = X86::MOV16rr;
2073   else if (X86::GR8RegClass.contains(DestReg, SrcReg)) {
2074     // Copying to or from a physical H register on x86-64 requires a NOREX
2075     // move.  Otherwise use a normal move.
2076     if ((isHReg(DestReg) || isHReg(SrcReg)) &&
2077         TM.getSubtarget<X86Subtarget>().is64Bit())
2078       Opc = X86::MOV8rr_NOREX;
2079     else
2080       Opc = X86::MOV8rr;
2081   } else if (X86::VR128RegClass.contains(DestReg, SrcReg))
2082     Opc = X86::MOVAPSrr;
2083   else if (X86::VR64RegClass.contains(DestReg, SrcReg))
2084     Opc = X86::MMX_MOVQ64rr;
2085
2086   if (Opc) {
2087     BuildMI(MBB, MI, DL, get(Opc), DestReg)
2088       .addReg(SrcReg, getKillRegState(KillSrc));
2089     return;
2090   }
2091
2092   // Moving EFLAGS to / from another register requires a push and a pop.
2093   if (SrcReg == X86::EFLAGS) {
2094     if (X86::GR64RegClass.contains(DestReg)) {
2095       BuildMI(MBB, MI, DL, get(X86::PUSHF64));
2096       BuildMI(MBB, MI, DL, get(X86::POP64r), DestReg);
2097       return;
2098     } else if (X86::GR32RegClass.contains(DestReg)) {
2099       BuildMI(MBB, MI, DL, get(X86::PUSHF32));
2100       BuildMI(MBB, MI, DL, get(X86::POP32r), DestReg);
2101       return;
2102     }
2103   }
2104   if (DestReg == X86::EFLAGS) {
2105     if (X86::GR64RegClass.contains(SrcReg)) {
2106       BuildMI(MBB, MI, DL, get(X86::PUSH64r))
2107         .addReg(SrcReg, getKillRegState(KillSrc));
2108       BuildMI(MBB, MI, DL, get(X86::POPF64));
2109       return;
2110     } else if (X86::GR32RegClass.contains(SrcReg)) {
2111       BuildMI(MBB, MI, DL, get(X86::PUSH32r))
2112         .addReg(SrcReg, getKillRegState(KillSrc));
2113       BuildMI(MBB, MI, DL, get(X86::POPF32));
2114       return;
2115     }
2116   }
2117
2118   DEBUG(dbgs() << "Cannot copy " << RI.getName(SrcReg)
2119                << " to " << RI.getName(DestReg) << '\n');
2120   llvm_unreachable("Cannot emit physreg copy instruction");
2121 }
2122
2123 static unsigned getLoadStoreRegOpcode(unsigned Reg,
2124                                       const TargetRegisterClass *RC,
2125                                       bool isStackAligned,
2126                                       const TargetMachine &TM,
2127                                       bool load) {
2128   if (RC == &X86::GR64RegClass || RC == &X86::GR64_NOSPRegClass) {
2129     return load ? X86::MOV64rm : X86::MOV64mr;
2130   } else if (RC == &X86::GR32RegClass || RC == &X86::GR32_NOSPRegClass) {
2131     return load ? X86::MOV32rm : X86::MOV32mr;
2132   } else if (RC == &X86::GR16RegClass) {
2133     return load ? X86::MOV16rm : X86::MOV16mr;
2134   } else if (RC == &X86::GR8RegClass) {
2135     // Copying to or from a physical H register on x86-64 requires a NOREX
2136     // move.  Otherwise use a normal move.
2137     if (isHReg(Reg) &&
2138         TM.getSubtarget<X86Subtarget>().is64Bit())
2139       return load ? X86::MOV8rm_NOREX : X86::MOV8mr_NOREX;
2140     else
2141       return load ? X86::MOV8rm : X86::MOV8mr;
2142   } else if (RC == &X86::GR64_ABCDRegClass) {
2143     return load ? X86::MOV64rm : X86::MOV64mr;
2144   } else if (RC == &X86::GR32_ABCDRegClass) {
2145     return load ? X86::MOV32rm : X86::MOV32mr;
2146   } else if (RC == &X86::GR16_ABCDRegClass) {
2147     return load ? X86::MOV16rm : X86::MOV16mr;
2148   } else if (RC == &X86::GR8_ABCD_LRegClass) {
2149     return load ? X86::MOV8rm :X86::MOV8mr;
2150   } else if (RC == &X86::GR8_ABCD_HRegClass) {
2151     if (TM.getSubtarget<X86Subtarget>().is64Bit())
2152       return load ? X86::MOV8rm_NOREX : X86::MOV8mr_NOREX;
2153     else
2154       return load ? X86::MOV8rm : X86::MOV8mr;
2155   } else if (RC == &X86::GR64_NOREXRegClass ||
2156              RC == &X86::GR64_NOREX_NOSPRegClass) {
2157     return load ? X86::MOV64rm : X86::MOV64mr;
2158   } else if (RC == &X86::GR32_NOREXRegClass) {
2159     return load ? X86::MOV32rm : X86::MOV32mr;
2160   } else if (RC == &X86::GR16_NOREXRegClass) {
2161     return load ? X86::MOV16rm : X86::MOV16mr;
2162   } else if (RC == &X86::GR8_NOREXRegClass) {
2163     return load ? X86::MOV8rm : X86::MOV8mr;
2164   } else if (RC == &X86::GR64_TCRegClass) {
2165     return load ? X86::MOV64rm_TC : X86::MOV64mr_TC;
2166   } else if (RC == &X86::GR32_TCRegClass) {
2167     return load ? X86::MOV32rm_TC : X86::MOV32mr_TC;
2168   } else if (RC == &X86::RFP80RegClass) {
2169     return load ? X86::LD_Fp80m : X86::ST_FpP80m;
2170   } else if (RC == &X86::RFP64RegClass) {
2171     return load ? X86::LD_Fp64m : X86::ST_Fp64m;
2172   } else if (RC == &X86::RFP32RegClass) {
2173     return load ? X86::LD_Fp32m : X86::ST_Fp32m;
2174   } else if (RC == &X86::FR32RegClass) {
2175     return load ? X86::MOVSSrm : X86::MOVSSmr;
2176   } else if (RC == &X86::FR64RegClass) {
2177     return load ? X86::MOVSDrm : X86::MOVSDmr;
2178   } else if (RC == &X86::VR128RegClass) {
2179     // If stack is realigned we can use aligned stores.
2180     if (isStackAligned)
2181       return load ? X86::MOVAPSrm : X86::MOVAPSmr;
2182     else
2183       return load ? X86::MOVUPSrm : X86::MOVUPSmr;
2184   } else if (RC == &X86::VR64RegClass) {
2185     return load ? X86::MMX_MOVQ64rm : X86::MMX_MOVQ64mr;
2186   } else {
2187     llvm_unreachable("Unknown regclass");
2188   }
2189 }
2190
2191 static unsigned getStoreRegOpcode(unsigned SrcReg,
2192                                   const TargetRegisterClass *RC,
2193                                   bool isStackAligned,
2194                                   TargetMachine &TM) {
2195   return getLoadStoreRegOpcode(SrcReg, RC, isStackAligned, TM, false);
2196 }
2197
2198
2199 static unsigned getLoadRegOpcode(unsigned DestReg,
2200                                  const TargetRegisterClass *RC,
2201                                  bool isStackAligned,
2202                                  const TargetMachine &TM) {
2203   return getLoadStoreRegOpcode(DestReg, RC, isStackAligned, TM, true);
2204 }
2205
2206 void X86InstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
2207                                        MachineBasicBlock::iterator MI,
2208                                        unsigned SrcReg, bool isKill, int FrameIdx,
2209                                        const TargetRegisterClass *RC,
2210                                        const TargetRegisterInfo *TRI) const {
2211   const MachineFunction &MF = *MBB.getParent();
2212   bool isAligned = (RI.getStackAlignment() >= 16) || RI.canRealignStack(MF);
2213   unsigned Opc = getStoreRegOpcode(SrcReg, RC, isAligned, TM);
2214   DebugLoc DL = MBB.findDebugLoc(MI);
2215   addFrameReference(BuildMI(MBB, MI, DL, get(Opc)), FrameIdx)
2216     .addReg(SrcReg, getKillRegState(isKill));
2217 }
2218
2219 void X86InstrInfo::storeRegToAddr(MachineFunction &MF, unsigned SrcReg,
2220                                   bool isKill,
2221                                   SmallVectorImpl<MachineOperand> &Addr,
2222                                   const TargetRegisterClass *RC,
2223                                   MachineInstr::mmo_iterator MMOBegin,
2224                                   MachineInstr::mmo_iterator MMOEnd,
2225                                   SmallVectorImpl<MachineInstr*> &NewMIs) const {
2226   bool isAligned = *MMOBegin && (*MMOBegin)->getAlignment() >= 16;
2227   unsigned Opc = getStoreRegOpcode(SrcReg, RC, isAligned, TM);
2228   DebugLoc DL;
2229   MachineInstrBuilder MIB = BuildMI(MF, DL, get(Opc));
2230   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
2231     MIB.addOperand(Addr[i]);
2232   MIB.addReg(SrcReg, getKillRegState(isKill));
2233   (*MIB).setMemRefs(MMOBegin, MMOEnd);
2234   NewMIs.push_back(MIB);
2235 }
2236
2237
2238 void X86InstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
2239                                         MachineBasicBlock::iterator MI,
2240                                         unsigned DestReg, int FrameIdx,
2241                                         const TargetRegisterClass *RC,
2242                                         const TargetRegisterInfo *TRI) const {
2243   const MachineFunction &MF = *MBB.getParent();
2244   bool isAligned = (RI.getStackAlignment() >= 16) || RI.canRealignStack(MF);
2245   unsigned Opc = getLoadRegOpcode(DestReg, RC, isAligned, TM);
2246   DebugLoc DL = MBB.findDebugLoc(MI);
2247   addFrameReference(BuildMI(MBB, MI, DL, get(Opc), DestReg), FrameIdx);
2248 }
2249
2250 void X86InstrInfo::loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
2251                                  SmallVectorImpl<MachineOperand> &Addr,
2252                                  const TargetRegisterClass *RC,
2253                                  MachineInstr::mmo_iterator MMOBegin,
2254                                  MachineInstr::mmo_iterator MMOEnd,
2255                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
2256   bool isAligned = *MMOBegin && (*MMOBegin)->getAlignment() >= 16;
2257   unsigned Opc = getLoadRegOpcode(DestReg, RC, isAligned, TM);
2258   DebugLoc DL;
2259   MachineInstrBuilder MIB = BuildMI(MF, DL, get(Opc), DestReg);
2260   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
2261     MIB.addOperand(Addr[i]);
2262   (*MIB).setMemRefs(MMOBegin, MMOEnd);
2263   NewMIs.push_back(MIB);
2264 }
2265
2266 bool X86InstrInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
2267                                              MachineBasicBlock::iterator MI,
2268                                         const std::vector<CalleeSavedInfo> &CSI,
2269                                           const TargetRegisterInfo *TRI) const {
2270   if (CSI.empty())
2271     return false;
2272
2273   DebugLoc DL = MBB.findDebugLoc(MI);
2274
2275   bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
2276   bool isWin64 = TM.getSubtarget<X86Subtarget>().isTargetWin64();
2277   unsigned SlotSize = is64Bit ? 8 : 4;
2278
2279   MachineFunction &MF = *MBB.getParent();
2280   unsigned FPReg = RI.getFrameRegister(MF);
2281   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2282   unsigned CalleeFrameSize = 0;
2283   
2284   unsigned Opc = is64Bit ? X86::PUSH64r : X86::PUSH32r;
2285   for (unsigned i = CSI.size(); i != 0; --i) {
2286     unsigned Reg = CSI[i-1].getReg();
2287     // Add the callee-saved register as live-in. It's killed at the spill.
2288     MBB.addLiveIn(Reg);
2289     if (Reg == FPReg)
2290       // X86RegisterInfo::emitPrologue will handle spilling of frame register.
2291       continue;
2292     if (!X86::VR128RegClass.contains(Reg) && !isWin64) {
2293       CalleeFrameSize += SlotSize;
2294       BuildMI(MBB, MI, DL, get(Opc)).addReg(Reg, RegState::Kill);
2295     } else {
2296       storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
2297                           &X86::VR128RegClass, &RI);
2298     }
2299   }
2300
2301   X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
2302   return true;
2303 }
2304
2305 bool X86InstrInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
2306                                                MachineBasicBlock::iterator MI,
2307                                         const std::vector<CalleeSavedInfo> &CSI,
2308                                           const TargetRegisterInfo *TRI) const {
2309   if (CSI.empty())
2310     return false;
2311
2312   DebugLoc DL = MBB.findDebugLoc(MI);
2313
2314   MachineFunction &MF = *MBB.getParent();
2315   unsigned FPReg = RI.getFrameRegister(MF);
2316   bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
2317   bool isWin64 = TM.getSubtarget<X86Subtarget>().isTargetWin64();
2318   unsigned Opc = is64Bit ? X86::POP64r : X86::POP32r;
2319   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
2320     unsigned Reg = CSI[i].getReg();
2321     if (Reg == FPReg)
2322       // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
2323       continue;
2324     if (!X86::VR128RegClass.contains(Reg) && !isWin64) {
2325       BuildMI(MBB, MI, DL, get(Opc), Reg);
2326     } else {
2327       loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
2328                            &X86::VR128RegClass, &RI);
2329     }
2330   }
2331   return true;
2332 }
2333
2334 MachineInstr*
2335 X86InstrInfo::emitFrameIndexDebugValue(MachineFunction &MF,
2336                                        int FrameIx, uint64_t Offset,
2337                                        const MDNode *MDPtr,
2338                                        DebugLoc DL) const {
2339   X86AddressMode AM;
2340   AM.BaseType = X86AddressMode::FrameIndexBase;
2341   AM.Base.FrameIndex = FrameIx;
2342   MachineInstrBuilder MIB = BuildMI(MF, DL, get(X86::DBG_VALUE));
2343   addFullAddress(MIB, AM).addImm(Offset).addMetadata(MDPtr);
2344   return &*MIB;
2345 }
2346
2347 static MachineInstr *FuseTwoAddrInst(MachineFunction &MF, unsigned Opcode,
2348                                      const SmallVectorImpl<MachineOperand> &MOs,
2349                                      MachineInstr *MI,
2350                                      const TargetInstrInfo &TII) {
2351   // Create the base instruction with the memory operand as the first part.
2352   MachineInstr *NewMI = MF.CreateMachineInstr(TII.get(Opcode),
2353                                               MI->getDebugLoc(), true);
2354   MachineInstrBuilder MIB(NewMI);
2355   unsigned NumAddrOps = MOs.size();
2356   for (unsigned i = 0; i != NumAddrOps; ++i)
2357     MIB.addOperand(MOs[i]);
2358   if (NumAddrOps < 4)  // FrameIndex only
2359     addOffset(MIB, 0);
2360   
2361   // Loop over the rest of the ri operands, converting them over.
2362   unsigned NumOps = MI->getDesc().getNumOperands()-2;
2363   for (unsigned i = 0; i != NumOps; ++i) {
2364     MachineOperand &MO = MI->getOperand(i+2);
2365     MIB.addOperand(MO);
2366   }
2367   for (unsigned i = NumOps+2, e = MI->getNumOperands(); i != e; ++i) {
2368     MachineOperand &MO = MI->getOperand(i);
2369     MIB.addOperand(MO);
2370   }
2371   return MIB;
2372 }
2373
2374 static MachineInstr *FuseInst(MachineFunction &MF,
2375                               unsigned Opcode, unsigned OpNo,
2376                               const SmallVectorImpl<MachineOperand> &MOs,
2377                               MachineInstr *MI, const TargetInstrInfo &TII) {
2378   MachineInstr *NewMI = MF.CreateMachineInstr(TII.get(Opcode),
2379                                               MI->getDebugLoc(), true);
2380   MachineInstrBuilder MIB(NewMI);
2381   
2382   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2383     MachineOperand &MO = MI->getOperand(i);
2384     if (i == OpNo) {
2385       assert(MO.isReg() && "Expected to fold into reg operand!");
2386       unsigned NumAddrOps = MOs.size();
2387       for (unsigned i = 0; i != NumAddrOps; ++i)
2388         MIB.addOperand(MOs[i]);
2389       if (NumAddrOps < 4)  // FrameIndex only
2390         addOffset(MIB, 0);
2391     } else {
2392       MIB.addOperand(MO);
2393     }
2394   }
2395   return MIB;
2396 }
2397
2398 static MachineInstr *MakeM0Inst(const TargetInstrInfo &TII, unsigned Opcode,
2399                                 const SmallVectorImpl<MachineOperand> &MOs,
2400                                 MachineInstr *MI) {
2401   MachineFunction &MF = *MI->getParent()->getParent();
2402   MachineInstrBuilder MIB = BuildMI(MF, MI->getDebugLoc(), TII.get(Opcode));
2403
2404   unsigned NumAddrOps = MOs.size();
2405   for (unsigned i = 0; i != NumAddrOps; ++i)
2406     MIB.addOperand(MOs[i]);
2407   if (NumAddrOps < 4)  // FrameIndex only
2408     addOffset(MIB, 0);
2409   return MIB.addImm(0);
2410 }
2411
2412 MachineInstr*
2413 X86InstrInfo::foldMemoryOperandImpl(MachineFunction &MF,
2414                                     MachineInstr *MI, unsigned i,
2415                                     const SmallVectorImpl<MachineOperand> &MOs,
2416                                     unsigned Size, unsigned Align) const {
2417   const DenseMap<unsigned*, std::pair<unsigned,unsigned> > *OpcodeTablePtr=NULL;
2418   bool isTwoAddrFold = false;
2419   unsigned NumOps = MI->getDesc().getNumOperands();
2420   bool isTwoAddr = NumOps > 1 &&
2421     MI->getDesc().getOperandConstraint(1, TOI::TIED_TO) != -1;
2422
2423   MachineInstr *NewMI = NULL;
2424   // Folding a memory location into the two-address part of a two-address
2425   // instruction is different than folding it other places.  It requires
2426   // replacing the *two* registers with the memory location.
2427   if (isTwoAddr && NumOps >= 2 && i < 2 &&
2428       MI->getOperand(0).isReg() &&
2429       MI->getOperand(1).isReg() &&
2430       MI->getOperand(0).getReg() == MI->getOperand(1).getReg()) { 
2431     OpcodeTablePtr = &RegOp2MemOpTable2Addr;
2432     isTwoAddrFold = true;
2433   } else if (i == 0) { // If operand 0
2434     if (MI->getOpcode() == X86::MOV64r0)
2435       NewMI = MakeM0Inst(*this, X86::MOV64mi32, MOs, MI);
2436     else if (MI->getOpcode() == X86::MOV32r0)
2437       NewMI = MakeM0Inst(*this, X86::MOV32mi, MOs, MI);
2438     else if (MI->getOpcode() == X86::MOV16r0)
2439       NewMI = MakeM0Inst(*this, X86::MOV16mi, MOs, MI);
2440     else if (MI->getOpcode() == X86::MOV8r0)
2441       NewMI = MakeM0Inst(*this, X86::MOV8mi, MOs, MI);
2442     if (NewMI)
2443       return NewMI;
2444     
2445     OpcodeTablePtr = &RegOp2MemOpTable0;
2446   } else if (i == 1) {
2447     OpcodeTablePtr = &RegOp2MemOpTable1;
2448   } else if (i == 2) {
2449     OpcodeTablePtr = &RegOp2MemOpTable2;
2450   }
2451   
2452   // If table selected...
2453   if (OpcodeTablePtr) {
2454     // Find the Opcode to fuse
2455     DenseMap<unsigned*, std::pair<unsigned,unsigned> >::const_iterator I =
2456       OpcodeTablePtr->find((unsigned*)MI->getOpcode());
2457     if (I != OpcodeTablePtr->end()) {
2458       unsigned Opcode = I->second.first;
2459       unsigned MinAlign = I->second.second;
2460       if (Align < MinAlign)
2461         return NULL;
2462       bool NarrowToMOV32rm = false;
2463       if (Size) {
2464         unsigned RCSize =  MI->getDesc().OpInfo[i].getRegClass(&RI)->getSize();
2465         if (Size < RCSize) {
2466           // Check if it's safe to fold the load. If the size of the object is
2467           // narrower than the load width, then it's not.
2468           if (Opcode != X86::MOV64rm || RCSize != 8 || Size != 4)
2469             return NULL;
2470           // If this is a 64-bit load, but the spill slot is 32, then we can do
2471           // a 32-bit load which is implicitly zero-extended. This likely is due
2472           // to liveintervalanalysis remat'ing a load from stack slot.
2473           if (MI->getOperand(0).getSubReg() || MI->getOperand(1).getSubReg())
2474             return NULL;
2475           Opcode = X86::MOV32rm;
2476           NarrowToMOV32rm = true;
2477         }
2478       }
2479
2480       if (isTwoAddrFold)
2481         NewMI = FuseTwoAddrInst(MF, Opcode, MOs, MI, *this);
2482       else
2483         NewMI = FuseInst(MF, Opcode, i, MOs, MI, *this);
2484
2485       if (NarrowToMOV32rm) {
2486         // If this is the special case where we use a MOV32rm to load a 32-bit
2487         // value and zero-extend the top bits. Change the destination register
2488         // to a 32-bit one.
2489         unsigned DstReg = NewMI->getOperand(0).getReg();
2490         if (TargetRegisterInfo::isPhysicalRegister(DstReg))
2491           NewMI->getOperand(0).setReg(RI.getSubReg(DstReg,
2492                                                    X86::sub_32bit));
2493         else
2494           NewMI->getOperand(0).setSubReg(X86::sub_32bit);
2495       }
2496       return NewMI;
2497     }
2498   }
2499   
2500   // No fusion 
2501   if (PrintFailedFusing && !MI->isCopy())
2502     dbgs() << "We failed to fuse operand " << i << " in " << *MI;
2503   return NULL;
2504 }
2505
2506
2507 MachineInstr* X86InstrInfo::foldMemoryOperandImpl(MachineFunction &MF,
2508                                                   MachineInstr *MI,
2509                                            const SmallVectorImpl<unsigned> &Ops,
2510                                                   int FrameIndex) const {
2511   // Check switch flag 
2512   if (NoFusing) return NULL;
2513
2514   if (!MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize))
2515     switch (MI->getOpcode()) {
2516     case X86::CVTSD2SSrr:
2517     case X86::Int_CVTSD2SSrr:
2518     case X86::CVTSS2SDrr:
2519     case X86::Int_CVTSS2SDrr:
2520     case X86::RCPSSr:
2521     case X86::RCPSSr_Int:
2522     case X86::ROUNDSDr_Int:
2523     case X86::ROUNDSSr_Int:
2524     case X86::RSQRTSSr:
2525     case X86::RSQRTSSr_Int:
2526     case X86::SQRTSSr:
2527     case X86::SQRTSSr_Int:
2528       return 0;
2529     }
2530
2531   const MachineFrameInfo *MFI = MF.getFrameInfo();
2532   unsigned Size = MFI->getObjectSize(FrameIndex);
2533   unsigned Alignment = MFI->getObjectAlignment(FrameIndex);
2534   if (Ops.size() == 2 && Ops[0] == 0 && Ops[1] == 1) {
2535     unsigned NewOpc = 0;
2536     unsigned RCSize = 0;
2537     switch (MI->getOpcode()) {
2538     default: return NULL;
2539     case X86::TEST8rr:  NewOpc = X86::CMP8ri; RCSize = 1; break;
2540     case X86::TEST16rr: NewOpc = X86::CMP16ri8; RCSize = 2; break;
2541     case X86::TEST32rr: NewOpc = X86::CMP32ri8; RCSize = 4; break;
2542     case X86::TEST64rr: NewOpc = X86::CMP64ri8; RCSize = 8; break;
2543     }
2544     // Check if it's safe to fold the load. If the size of the object is
2545     // narrower than the load width, then it's not.
2546     if (Size < RCSize)
2547       return NULL;
2548     // Change to CMPXXri r, 0 first.
2549     MI->setDesc(get(NewOpc));
2550     MI->getOperand(1).ChangeToImmediate(0);
2551   } else if (Ops.size() != 1)
2552     return NULL;
2553
2554   SmallVector<MachineOperand,4> MOs;
2555   MOs.push_back(MachineOperand::CreateFI(FrameIndex));
2556   return foldMemoryOperandImpl(MF, MI, Ops[0], MOs, Size, Alignment);
2557 }
2558
2559 MachineInstr* X86InstrInfo::foldMemoryOperandImpl(MachineFunction &MF,
2560                                                   MachineInstr *MI,
2561                                            const SmallVectorImpl<unsigned> &Ops,
2562                                                   MachineInstr *LoadMI) const {
2563   // Check switch flag 
2564   if (NoFusing) return NULL;
2565
2566   if (!MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize))
2567     switch (MI->getOpcode()) {
2568     case X86::CVTSD2SSrr:
2569     case X86::Int_CVTSD2SSrr:
2570     case X86::CVTSS2SDrr:
2571     case X86::Int_CVTSS2SDrr:
2572     case X86::RCPSSr:
2573     case X86::RCPSSr_Int:
2574     case X86::ROUNDSDr_Int:
2575     case X86::ROUNDSSr_Int:
2576     case X86::RSQRTSSr:
2577     case X86::RSQRTSSr_Int:
2578     case X86::SQRTSSr:
2579     case X86::SQRTSSr_Int:
2580       return 0;
2581     }
2582
2583   // Determine the alignment of the load.
2584   unsigned Alignment = 0;
2585   if (LoadMI->hasOneMemOperand())
2586     Alignment = (*LoadMI->memoperands_begin())->getAlignment();
2587   else
2588     switch (LoadMI->getOpcode()) {
2589     case X86::V_SET0PS:
2590     case X86::V_SET0PD:
2591     case X86::V_SET0PI:
2592     case X86::V_SETALLONES:
2593       Alignment = 16;
2594       break;
2595     case X86::FsFLD0SD:
2596       Alignment = 8;
2597       break;
2598     case X86::FsFLD0SS:
2599       Alignment = 4;
2600       break;
2601     default:
2602       llvm_unreachable("Don't know how to fold this instruction!");
2603     }
2604   if (Ops.size() == 2 && Ops[0] == 0 && Ops[1] == 1) {
2605     unsigned NewOpc = 0;
2606     switch (MI->getOpcode()) {
2607     default: return NULL;
2608     case X86::TEST8rr:  NewOpc = X86::CMP8ri; break;
2609     case X86::TEST16rr: NewOpc = X86::CMP16ri8; break;
2610     case X86::TEST32rr: NewOpc = X86::CMP32ri8; break;
2611     case X86::TEST64rr: NewOpc = X86::CMP64ri8; break;
2612     }
2613     // Change to CMPXXri r, 0 first.
2614     MI->setDesc(get(NewOpc));
2615     MI->getOperand(1).ChangeToImmediate(0);
2616   } else if (Ops.size() != 1)
2617     return NULL;
2618
2619   SmallVector<MachineOperand,X86::AddrNumOperands> MOs;
2620   switch (LoadMI->getOpcode()) {
2621   case X86::V_SET0PS:
2622   case X86::V_SET0PD:
2623   case X86::V_SET0PI:
2624   case X86::V_SETALLONES:
2625   case X86::FsFLD0SD:
2626   case X86::FsFLD0SS: {
2627     // Folding a V_SET0P? or V_SETALLONES as a load, to ease register pressure.
2628     // Create a constant-pool entry and operands to load from it.
2629
2630     // Medium and large mode can't fold loads this way.
2631     if (TM.getCodeModel() != CodeModel::Small &&
2632         TM.getCodeModel() != CodeModel::Kernel)
2633       return NULL;
2634
2635     // x86-32 PIC requires a PIC base register for constant pools.
2636     unsigned PICBase = 0;
2637     if (TM.getRelocationModel() == Reloc::PIC_) {
2638       if (TM.getSubtarget<X86Subtarget>().is64Bit())
2639         PICBase = X86::RIP;
2640       else
2641         // FIXME: PICBase = TM.getInstrInfo()->getGlobalBaseReg(&MF);
2642         // This doesn't work for several reasons.
2643         // 1. GlobalBaseReg may have been spilled.
2644         // 2. It may not be live at MI.
2645         return NULL;
2646     }
2647
2648     // Create a constant-pool entry.
2649     MachineConstantPool &MCP = *MF.getConstantPool();
2650     const Type *Ty;
2651     if (LoadMI->getOpcode() == X86::FsFLD0SS)
2652       Ty = Type::getFloatTy(MF.getFunction()->getContext());
2653     else if (LoadMI->getOpcode() == X86::FsFLD0SD)
2654       Ty = Type::getDoubleTy(MF.getFunction()->getContext());
2655     else
2656       Ty = VectorType::get(Type::getInt32Ty(MF.getFunction()->getContext()), 4);
2657     const Constant *C = LoadMI->getOpcode() == X86::V_SETALLONES ?
2658                     Constant::getAllOnesValue(Ty) :
2659                     Constant::getNullValue(Ty);
2660     unsigned CPI = MCP.getConstantPoolIndex(C, Alignment);
2661
2662     // Create operands to load from the constant pool entry.
2663     MOs.push_back(MachineOperand::CreateReg(PICBase, false));
2664     MOs.push_back(MachineOperand::CreateImm(1));
2665     MOs.push_back(MachineOperand::CreateReg(0, false));
2666     MOs.push_back(MachineOperand::CreateCPI(CPI, 0));
2667     MOs.push_back(MachineOperand::CreateReg(0, false));
2668     break;
2669   }
2670   default: {
2671     // Folding a normal load. Just copy the load's address operands.
2672     unsigned NumOps = LoadMI->getDesc().getNumOperands();
2673     for (unsigned i = NumOps - X86::AddrNumOperands; i != NumOps; ++i)
2674       MOs.push_back(LoadMI->getOperand(i));
2675     break;
2676   }
2677   }
2678   return foldMemoryOperandImpl(MF, MI, Ops[0], MOs, 0, Alignment);
2679 }
2680
2681
2682 bool X86InstrInfo::canFoldMemoryOperand(const MachineInstr *MI,
2683                                   const SmallVectorImpl<unsigned> &Ops) const {
2684   // Check switch flag 
2685   if (NoFusing) return 0;
2686
2687   if (Ops.size() == 2 && Ops[0] == 0 && Ops[1] == 1) {
2688     switch (MI->getOpcode()) {
2689     default: return false;
2690     case X86::TEST8rr: 
2691     case X86::TEST16rr:
2692     case X86::TEST32rr:
2693     case X86::TEST64rr:
2694       return true;
2695     }
2696   }
2697
2698   if (Ops.size() != 1)
2699     return false;
2700
2701   unsigned OpNum = Ops[0];
2702   unsigned Opc = MI->getOpcode();
2703   unsigned NumOps = MI->getDesc().getNumOperands();
2704   bool isTwoAddr = NumOps > 1 &&
2705     MI->getDesc().getOperandConstraint(1, TOI::TIED_TO) != -1;
2706
2707   // Folding a memory location into the two-address part of a two-address
2708   // instruction is different than folding it other places.  It requires
2709   // replacing the *two* registers with the memory location.
2710   const DenseMap<unsigned*, std::pair<unsigned,unsigned> > *OpcodeTablePtr=NULL;
2711   if (isTwoAddr && NumOps >= 2 && OpNum < 2) { 
2712     OpcodeTablePtr = &RegOp2MemOpTable2Addr;
2713   } else if (OpNum == 0) { // If operand 0
2714     switch (Opc) {
2715     case X86::MOV8r0:
2716     case X86::MOV16r0:
2717     case X86::MOV32r0:
2718     case X86::MOV64r0:
2719       return true;
2720     default: break;
2721     }
2722     OpcodeTablePtr = &RegOp2MemOpTable0;
2723   } else if (OpNum == 1) {
2724     OpcodeTablePtr = &RegOp2MemOpTable1;
2725   } else if (OpNum == 2) {
2726     OpcodeTablePtr = &RegOp2MemOpTable2;
2727   }
2728   
2729   if (OpcodeTablePtr) {
2730     // Find the Opcode to fuse
2731     DenseMap<unsigned*, std::pair<unsigned,unsigned> >::const_iterator I =
2732       OpcodeTablePtr->find((unsigned*)Opc);
2733     if (I != OpcodeTablePtr->end())
2734       return true;
2735   }
2736   return TargetInstrInfoImpl::canFoldMemoryOperand(MI, Ops);
2737 }
2738
2739 bool X86InstrInfo::unfoldMemoryOperand(MachineFunction &MF, MachineInstr *MI,
2740                                 unsigned Reg, bool UnfoldLoad, bool UnfoldStore,
2741                                 SmallVectorImpl<MachineInstr*> &NewMIs) const {
2742   DenseMap<unsigned*, std::pair<unsigned,unsigned> >::const_iterator I =
2743     MemOp2RegOpTable.find((unsigned*)MI->getOpcode());
2744   if (I == MemOp2RegOpTable.end())
2745     return false;
2746   unsigned Opc = I->second.first;
2747   unsigned Index = I->second.second & 0xf;
2748   bool FoldedLoad = I->second.second & (1 << 4);
2749   bool FoldedStore = I->second.second & (1 << 5);
2750   if (UnfoldLoad && !FoldedLoad)
2751     return false;
2752   UnfoldLoad &= FoldedLoad;
2753   if (UnfoldStore && !FoldedStore)
2754     return false;
2755   UnfoldStore &= FoldedStore;
2756
2757   const TargetInstrDesc &TID = get(Opc);
2758   const TargetOperandInfo &TOI = TID.OpInfo[Index];
2759   const TargetRegisterClass *RC = TOI.getRegClass(&RI);
2760   if (!MI->hasOneMemOperand() &&
2761       RC == &X86::VR128RegClass &&
2762       !TM.getSubtarget<X86Subtarget>().isUnalignedMemAccessFast())
2763     // Without memoperands, loadRegFromAddr and storeRegToStackSlot will
2764     // conservatively assume the address is unaligned. That's bad for
2765     // performance.
2766     return false;
2767   SmallVector<MachineOperand, X86::AddrNumOperands> AddrOps;
2768   SmallVector<MachineOperand,2> BeforeOps;
2769   SmallVector<MachineOperand,2> AfterOps;
2770   SmallVector<MachineOperand,4> ImpOps;
2771   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2772     MachineOperand &Op = MI->getOperand(i);
2773     if (i >= Index && i < Index + X86::AddrNumOperands)
2774       AddrOps.push_back(Op);
2775     else if (Op.isReg() && Op.isImplicit())
2776       ImpOps.push_back(Op);
2777     else if (i < Index)
2778       BeforeOps.push_back(Op);
2779     else if (i > Index)
2780       AfterOps.push_back(Op);
2781   }
2782
2783   // Emit the load instruction.
2784   if (UnfoldLoad) {
2785     std::pair<MachineInstr::mmo_iterator,
2786               MachineInstr::mmo_iterator> MMOs =
2787       MF.extractLoadMemRefs(MI->memoperands_begin(),
2788                             MI->memoperands_end());
2789     loadRegFromAddr(MF, Reg, AddrOps, RC, MMOs.first, MMOs.second, NewMIs);
2790     if (UnfoldStore) {
2791       // Address operands cannot be marked isKill.
2792       for (unsigned i = 1; i != 1 + X86::AddrNumOperands; ++i) {
2793         MachineOperand &MO = NewMIs[0]->getOperand(i);
2794         if (MO.isReg())
2795           MO.setIsKill(false);
2796       }
2797     }
2798   }
2799
2800   // Emit the data processing instruction.
2801   MachineInstr *DataMI = MF.CreateMachineInstr(TID, MI->getDebugLoc(), true);
2802   MachineInstrBuilder MIB(DataMI);
2803   
2804   if (FoldedStore)
2805     MIB.addReg(Reg, RegState::Define);
2806   for (unsigned i = 0, e = BeforeOps.size(); i != e; ++i)
2807     MIB.addOperand(BeforeOps[i]);
2808   if (FoldedLoad)
2809     MIB.addReg(Reg);
2810   for (unsigned i = 0, e = AfterOps.size(); i != e; ++i)
2811     MIB.addOperand(AfterOps[i]);
2812   for (unsigned i = 0, e = ImpOps.size(); i != e; ++i) {
2813     MachineOperand &MO = ImpOps[i];
2814     MIB.addReg(MO.getReg(),
2815                getDefRegState(MO.isDef()) |
2816                RegState::Implicit |
2817                getKillRegState(MO.isKill()) |
2818                getDeadRegState(MO.isDead()) |
2819                getUndefRegState(MO.isUndef()));
2820   }
2821   // Change CMP32ri r, 0 back to TEST32rr r, r, etc.
2822   unsigned NewOpc = 0;
2823   switch (DataMI->getOpcode()) {
2824   default: break;
2825   case X86::CMP64ri32:
2826   case X86::CMP64ri8:
2827   case X86::CMP32ri:
2828   case X86::CMP32ri8:
2829   case X86::CMP16ri:
2830   case X86::CMP16ri8:
2831   case X86::CMP8ri: {
2832     MachineOperand &MO0 = DataMI->getOperand(0);
2833     MachineOperand &MO1 = DataMI->getOperand(1);
2834     if (MO1.getImm() == 0) {
2835       switch (DataMI->getOpcode()) {
2836       default: break;
2837       case X86::CMP64ri8:
2838       case X86::CMP64ri32: NewOpc = X86::TEST64rr; break;
2839       case X86::CMP32ri8:
2840       case X86::CMP32ri:   NewOpc = X86::TEST32rr; break;
2841       case X86::CMP16ri8:
2842       case X86::CMP16ri:   NewOpc = X86::TEST16rr; break;
2843       case X86::CMP8ri:    NewOpc = X86::TEST8rr; break;
2844       }
2845       DataMI->setDesc(get(NewOpc));
2846       MO1.ChangeToRegister(MO0.getReg(), false);
2847     }
2848   }
2849   }
2850   NewMIs.push_back(DataMI);
2851
2852   // Emit the store instruction.
2853   if (UnfoldStore) {
2854     const TargetRegisterClass *DstRC = TID.OpInfo[0].getRegClass(&RI);
2855     std::pair<MachineInstr::mmo_iterator,
2856               MachineInstr::mmo_iterator> MMOs =
2857       MF.extractStoreMemRefs(MI->memoperands_begin(),
2858                              MI->memoperands_end());
2859     storeRegToAddr(MF, Reg, true, AddrOps, DstRC, MMOs.first, MMOs.second, NewMIs);
2860   }
2861
2862   return true;
2863 }
2864
2865 bool
2866 X86InstrInfo::unfoldMemoryOperand(SelectionDAG &DAG, SDNode *N,
2867                                   SmallVectorImpl<SDNode*> &NewNodes) const {
2868   if (!N->isMachineOpcode())
2869     return false;
2870
2871   DenseMap<unsigned*, std::pair<unsigned,unsigned> >::const_iterator I =
2872     MemOp2RegOpTable.find((unsigned*)N->getMachineOpcode());
2873   if (I == MemOp2RegOpTable.end())
2874     return false;
2875   unsigned Opc = I->second.first;
2876   unsigned Index = I->second.second & 0xf;
2877   bool FoldedLoad = I->second.second & (1 << 4);
2878   bool FoldedStore = I->second.second & (1 << 5);
2879   const TargetInstrDesc &TID = get(Opc);
2880   const TargetRegisterClass *RC = TID.OpInfo[Index].getRegClass(&RI);
2881   unsigned NumDefs = TID.NumDefs;
2882   std::vector<SDValue> AddrOps;
2883   std::vector<SDValue> BeforeOps;
2884   std::vector<SDValue> AfterOps;
2885   DebugLoc dl = N->getDebugLoc();
2886   unsigned NumOps = N->getNumOperands();
2887   for (unsigned i = 0; i != NumOps-1; ++i) {
2888     SDValue Op = N->getOperand(i);
2889     if (i >= Index-NumDefs && i < Index-NumDefs + X86::AddrNumOperands)
2890       AddrOps.push_back(Op);
2891     else if (i < Index-NumDefs)
2892       BeforeOps.push_back(Op);
2893     else if (i > Index-NumDefs)
2894       AfterOps.push_back(Op);
2895   }
2896   SDValue Chain = N->getOperand(NumOps-1);
2897   AddrOps.push_back(Chain);
2898
2899   // Emit the load instruction.
2900   SDNode *Load = 0;
2901   MachineFunction &MF = DAG.getMachineFunction();
2902   if (FoldedLoad) {
2903     EVT VT = *RC->vt_begin();
2904     std::pair<MachineInstr::mmo_iterator,
2905               MachineInstr::mmo_iterator> MMOs =
2906       MF.extractLoadMemRefs(cast<MachineSDNode>(N)->memoperands_begin(),
2907                             cast<MachineSDNode>(N)->memoperands_end());
2908     if (!(*MMOs.first) &&
2909         RC == &X86::VR128RegClass &&
2910         !TM.getSubtarget<X86Subtarget>().isUnalignedMemAccessFast())
2911       // Do not introduce a slow unaligned load.
2912       return false;
2913     bool isAligned = (*MMOs.first) && (*MMOs.first)->getAlignment() >= 16;
2914     Load = DAG.getMachineNode(getLoadRegOpcode(0, RC, isAligned, TM), dl,
2915                               VT, MVT::Other, &AddrOps[0], AddrOps.size());
2916     NewNodes.push_back(Load);
2917
2918     // Preserve memory reference information.
2919     cast<MachineSDNode>(Load)->setMemRefs(MMOs.first, MMOs.second);
2920   }
2921
2922   // Emit the data processing instruction.
2923   std::vector<EVT> VTs;
2924   const TargetRegisterClass *DstRC = 0;
2925   if (TID.getNumDefs() > 0) {
2926     DstRC = TID.OpInfo[0].getRegClass(&RI);
2927     VTs.push_back(*DstRC->vt_begin());
2928   }
2929   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
2930     EVT VT = N->getValueType(i);
2931     if (VT != MVT::Other && i >= (unsigned)TID.getNumDefs())
2932       VTs.push_back(VT);
2933   }
2934   if (Load)
2935     BeforeOps.push_back(SDValue(Load, 0));
2936   std::copy(AfterOps.begin(), AfterOps.end(), std::back_inserter(BeforeOps));
2937   SDNode *NewNode= DAG.getMachineNode(Opc, dl, VTs, &BeforeOps[0],
2938                                       BeforeOps.size());
2939   NewNodes.push_back(NewNode);
2940
2941   // Emit the store instruction.
2942   if (FoldedStore) {
2943     AddrOps.pop_back();
2944     AddrOps.push_back(SDValue(NewNode, 0));
2945     AddrOps.push_back(Chain);
2946     std::pair<MachineInstr::mmo_iterator,
2947               MachineInstr::mmo_iterator> MMOs =
2948       MF.extractStoreMemRefs(cast<MachineSDNode>(N)->memoperands_begin(),
2949                              cast<MachineSDNode>(N)->memoperands_end());
2950     if (!(*MMOs.first) &&
2951         RC == &X86::VR128RegClass &&
2952         !TM.getSubtarget<X86Subtarget>().isUnalignedMemAccessFast())
2953       // Do not introduce a slow unaligned store.
2954       return false;
2955     bool isAligned = (*MMOs.first) && (*MMOs.first)->getAlignment() >= 16;
2956     SDNode *Store = DAG.getMachineNode(getStoreRegOpcode(0, DstRC,
2957                                                          isAligned, TM),
2958                                        dl, MVT::Other,
2959                                        &AddrOps[0], AddrOps.size());
2960     NewNodes.push_back(Store);
2961
2962     // Preserve memory reference information.
2963     cast<MachineSDNode>(Load)->setMemRefs(MMOs.first, MMOs.second);
2964   }
2965
2966   return true;
2967 }
2968
2969 unsigned X86InstrInfo::getOpcodeAfterMemoryUnfold(unsigned Opc,
2970                                       bool UnfoldLoad, bool UnfoldStore,
2971                                       unsigned *LoadRegIndex) const {
2972   DenseMap<unsigned*, std::pair<unsigned,unsigned> >::const_iterator I =
2973     MemOp2RegOpTable.find((unsigned*)Opc);
2974   if (I == MemOp2RegOpTable.end())
2975     return 0;
2976   bool FoldedLoad = I->second.second & (1 << 4);
2977   bool FoldedStore = I->second.second & (1 << 5);
2978   if (UnfoldLoad && !FoldedLoad)
2979     return 0;
2980   if (UnfoldStore && !FoldedStore)
2981     return 0;
2982   if (LoadRegIndex)
2983     *LoadRegIndex = I->second.second & 0xf;
2984   return I->second.first;
2985 }
2986
2987 bool
2988 X86InstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
2989                                      int64_t &Offset1, int64_t &Offset2) const {
2990   if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
2991     return false;
2992   unsigned Opc1 = Load1->getMachineOpcode();
2993   unsigned Opc2 = Load2->getMachineOpcode();
2994   switch (Opc1) {
2995   default: return false;
2996   case X86::MOV8rm:
2997   case X86::MOV16rm:
2998   case X86::MOV32rm:
2999   case X86::MOV64rm:
3000   case X86::LD_Fp32m:
3001   case X86::LD_Fp64m:
3002   case X86::LD_Fp80m:
3003   case X86::MOVSSrm:
3004   case X86::MOVSDrm:
3005   case X86::MMX_MOVD64rm:
3006   case X86::MMX_MOVQ64rm:
3007   case X86::FsMOVAPSrm:
3008   case X86::FsMOVAPDrm:
3009   case X86::MOVAPSrm:
3010   case X86::MOVUPSrm:
3011   case X86::MOVUPSrm_Int:
3012   case X86::MOVAPDrm:
3013   case X86::MOVDQArm:
3014   case X86::MOVDQUrm:
3015   case X86::MOVDQUrm_Int:
3016     break;
3017   }
3018   switch (Opc2) {
3019   default: return false;
3020   case X86::MOV8rm:
3021   case X86::MOV16rm:
3022   case X86::MOV32rm:
3023   case X86::MOV64rm:
3024   case X86::LD_Fp32m:
3025   case X86::LD_Fp64m:
3026   case X86::LD_Fp80m:
3027   case X86::MOVSSrm:
3028   case X86::MOVSDrm:
3029   case X86::MMX_MOVD64rm:
3030   case X86::MMX_MOVQ64rm:
3031   case X86::FsMOVAPSrm:
3032   case X86::FsMOVAPDrm:
3033   case X86::MOVAPSrm:
3034   case X86::MOVUPSrm:
3035   case X86::MOVUPSrm_Int:
3036   case X86::MOVAPDrm:
3037   case X86::MOVDQArm:
3038   case X86::MOVDQUrm:
3039   case X86::MOVDQUrm_Int:
3040     break;
3041   }
3042
3043   // Check if chain operands and base addresses match.
3044   if (Load1->getOperand(0) != Load2->getOperand(0) ||
3045       Load1->getOperand(5) != Load2->getOperand(5))
3046     return false;
3047   // Segment operands should match as well.
3048   if (Load1->getOperand(4) != Load2->getOperand(4))
3049     return false;
3050   // Scale should be 1, Index should be Reg0.
3051   if (Load1->getOperand(1) == Load2->getOperand(1) &&
3052       Load1->getOperand(2) == Load2->getOperand(2)) {
3053     if (cast<ConstantSDNode>(Load1->getOperand(1))->getZExtValue() != 1)
3054       return false;
3055
3056     // Now let's examine the displacements.
3057     if (isa<ConstantSDNode>(Load1->getOperand(3)) &&
3058         isa<ConstantSDNode>(Load2->getOperand(3))) {
3059       Offset1 = cast<ConstantSDNode>(Load1->getOperand(3))->getSExtValue();
3060       Offset2 = cast<ConstantSDNode>(Load2->getOperand(3))->getSExtValue();
3061       return true;
3062     }
3063   }
3064   return false;
3065 }
3066
3067 bool X86InstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
3068                                            int64_t Offset1, int64_t Offset2,
3069                                            unsigned NumLoads) const {
3070   assert(Offset2 > Offset1);
3071   if ((Offset2 - Offset1) / 8 > 64)
3072     return false;
3073
3074   unsigned Opc1 = Load1->getMachineOpcode();
3075   unsigned Opc2 = Load2->getMachineOpcode();
3076   if (Opc1 != Opc2)
3077     return false;  // FIXME: overly conservative?
3078
3079   switch (Opc1) {
3080   default: break;
3081   case X86::LD_Fp32m:
3082   case X86::LD_Fp64m:
3083   case X86::LD_Fp80m:
3084   case X86::MMX_MOVD64rm:
3085   case X86::MMX_MOVQ64rm:
3086     return false;
3087   }
3088
3089   EVT VT = Load1->getValueType(0);
3090   switch (VT.getSimpleVT().SimpleTy) {
3091   default:
3092     // XMM registers. In 64-bit mode we can be a bit more aggressive since we
3093     // have 16 of them to play with.
3094     if (TM.getSubtargetImpl()->is64Bit()) {
3095       if (NumLoads >= 3)
3096         return false;
3097     } else if (NumLoads) {
3098       return false;
3099     }
3100     break;
3101   case MVT::i8:
3102   case MVT::i16:
3103   case MVT::i32:
3104   case MVT::i64:
3105   case MVT::f32:
3106   case MVT::f64:
3107     if (NumLoads)
3108       return false;
3109     break;
3110   }
3111
3112   return true;
3113 }
3114
3115
3116 bool X86InstrInfo::
3117 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
3118   assert(Cond.size() == 1 && "Invalid X86 branch condition!");
3119   X86::CondCode CC = static_cast<X86::CondCode>(Cond[0].getImm());
3120   if (CC == X86::COND_NE_OR_P || CC == X86::COND_NP_OR_E)
3121     return true;
3122   Cond[0].setImm(GetOppositeBranchCondition(CC));
3123   return false;
3124 }
3125
3126 bool X86InstrInfo::
3127 isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
3128   // FIXME: Return false for x87 stack register classes for now. We can't
3129   // allow any loads of these registers before FpGet_ST0_80.
3130   return !(RC == &X86::CCRRegClass || RC == &X86::RFP32RegClass ||
3131            RC == &X86::RFP64RegClass || RC == &X86::RFP80RegClass);
3132 }
3133
3134
3135 /// isX86_64ExtendedReg - Is the MachineOperand a x86-64 extended (r8 or higher)
3136 /// register?  e.g. r8, xmm8, xmm13, etc.
3137 bool X86InstrInfo::isX86_64ExtendedReg(unsigned RegNo) {
3138   switch (RegNo) {
3139   default: break;
3140   case X86::R8:    case X86::R9:    case X86::R10:   case X86::R11:
3141   case X86::R12:   case X86::R13:   case X86::R14:   case X86::R15:
3142   case X86::R8D:   case X86::R9D:   case X86::R10D:  case X86::R11D:
3143   case X86::R12D:  case X86::R13D:  case X86::R14D:  case X86::R15D:
3144   case X86::R8W:   case X86::R9W:   case X86::R10W:  case X86::R11W:
3145   case X86::R12W:  case X86::R13W:  case X86::R14W:  case X86::R15W:
3146   case X86::R8B:   case X86::R9B:   case X86::R10B:  case X86::R11B:
3147   case X86::R12B:  case X86::R13B:  case X86::R14B:  case X86::R15B:
3148   case X86::XMM8:  case X86::XMM9:  case X86::XMM10: case X86::XMM11:
3149   case X86::XMM12: case X86::XMM13: case X86::XMM14: case X86::XMM15:
3150   case X86::YMM8:  case X86::YMM9:  case X86::YMM10: case X86::YMM11:
3151   case X86::YMM12: case X86::YMM13: case X86::YMM14: case X86::YMM15:
3152     return true;
3153   }
3154   return false;
3155 }
3156
3157
3158 /// determineREX - Determine if the MachineInstr has to be encoded with a X86-64
3159 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
3160 /// size, and 3) use of X86-64 extended registers.
3161 unsigned X86InstrInfo::determineREX(const MachineInstr &MI) {
3162   unsigned REX = 0;
3163   const TargetInstrDesc &Desc = MI.getDesc();
3164
3165   // Pseudo instructions do not need REX prefix byte.
3166   if ((Desc.TSFlags & X86II::FormMask) == X86II::Pseudo)
3167     return 0;
3168   if (Desc.TSFlags & X86II::REX_W)
3169     REX |= 1 << 3;
3170
3171   unsigned NumOps = Desc.getNumOperands();
3172   if (NumOps) {
3173     bool isTwoAddr = NumOps > 1 &&
3174       Desc.getOperandConstraint(1, TOI::TIED_TO) != -1;
3175
3176     // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
3177     unsigned i = isTwoAddr ? 1 : 0;
3178     for (unsigned e = NumOps; i != e; ++i) {
3179       const MachineOperand& MO = MI.getOperand(i);
3180       if (MO.isReg()) {
3181         unsigned Reg = MO.getReg();
3182         if (isX86_64NonExtLowByteReg(Reg))
3183           REX |= 0x40;
3184       }
3185     }
3186
3187     switch (Desc.TSFlags & X86II::FormMask) {
3188     case X86II::MRMInitReg:
3189       if (isX86_64ExtendedReg(MI.getOperand(0)))
3190         REX |= (1 << 0) | (1 << 2);
3191       break;
3192     case X86II::MRMSrcReg: {
3193       if (isX86_64ExtendedReg(MI.getOperand(0)))
3194         REX |= 1 << 2;
3195       i = isTwoAddr ? 2 : 1;
3196       for (unsigned e = NumOps; i != e; ++i) {
3197         const MachineOperand& MO = MI.getOperand(i);
3198         if (isX86_64ExtendedReg(MO))
3199           REX |= 1 << 0;
3200       }
3201       break;
3202     }
3203     case X86II::MRMSrcMem: {
3204       if (isX86_64ExtendedReg(MI.getOperand(0)))
3205         REX |= 1 << 2;
3206       unsigned Bit = 0;
3207       i = isTwoAddr ? 2 : 1;
3208       for (; i != NumOps; ++i) {
3209         const MachineOperand& MO = MI.getOperand(i);
3210         if (MO.isReg()) {
3211           if (isX86_64ExtendedReg(MO))
3212             REX |= 1 << Bit;
3213           Bit++;
3214         }
3215       }
3216       break;
3217     }
3218     case X86II::MRM0m: case X86II::MRM1m:
3219     case X86II::MRM2m: case X86II::MRM3m:
3220     case X86II::MRM4m: case X86II::MRM5m:
3221     case X86II::MRM6m: case X86II::MRM7m:
3222     case X86II::MRMDestMem: {
3223       unsigned e = (isTwoAddr ? X86::AddrNumOperands+1 : X86::AddrNumOperands);
3224       i = isTwoAddr ? 1 : 0;
3225       if (NumOps > e && isX86_64ExtendedReg(MI.getOperand(e)))
3226         REX |= 1 << 2;
3227       unsigned Bit = 0;
3228       for (; i != e; ++i) {
3229         const MachineOperand& MO = MI.getOperand(i);
3230         if (MO.isReg()) {
3231           if (isX86_64ExtendedReg(MO))
3232             REX |= 1 << Bit;
3233           Bit++;
3234         }
3235       }
3236       break;
3237     }
3238     default: {
3239       if (isX86_64ExtendedReg(MI.getOperand(0)))
3240         REX |= 1 << 0;
3241       i = isTwoAddr ? 2 : 1;
3242       for (unsigned e = NumOps; i != e; ++i) {
3243         const MachineOperand& MO = MI.getOperand(i);
3244         if (isX86_64ExtendedReg(MO))
3245           REX |= 1 << 2;
3246       }
3247       break;
3248     }
3249     }
3250   }
3251   return REX;
3252 }
3253
3254 /// sizePCRelativeBlockAddress - This method returns the size of a PC
3255 /// relative block address instruction
3256 ///
3257 static unsigned sizePCRelativeBlockAddress() {
3258   return 4;
3259 }
3260
3261 /// sizeGlobalAddress - Give the size of the emission of this global address
3262 ///
3263 static unsigned sizeGlobalAddress(bool dword) {
3264   return dword ? 8 : 4;
3265 }
3266
3267 /// sizeConstPoolAddress - Give the size of the emission of this constant
3268 /// pool address
3269 ///
3270 static unsigned sizeConstPoolAddress(bool dword) {
3271   return dword ? 8 : 4;
3272 }
3273
3274 /// sizeExternalSymbolAddress - Give the size of the emission of this external
3275 /// symbol
3276 ///
3277 static unsigned sizeExternalSymbolAddress(bool dword) {
3278   return dword ? 8 : 4;
3279 }
3280
3281 /// sizeJumpTableAddress - Give the size of the emission of this jump
3282 /// table address
3283 ///
3284 static unsigned sizeJumpTableAddress(bool dword) {
3285   return dword ? 8 : 4;
3286 }
3287
3288 static unsigned sizeConstant(unsigned Size) {
3289   return Size;
3290 }
3291
3292 static unsigned sizeRegModRMByte(){
3293   return 1;
3294 }
3295
3296 static unsigned sizeSIBByte(){
3297   return 1;
3298 }
3299
3300 static unsigned getDisplacementFieldSize(const MachineOperand *RelocOp) {
3301   unsigned FinalSize = 0;
3302   // If this is a simple integer displacement that doesn't require a relocation.
3303   if (!RelocOp) {
3304     FinalSize += sizeConstant(4);
3305     return FinalSize;
3306   }
3307   
3308   // Otherwise, this is something that requires a relocation.
3309   if (RelocOp->isGlobal()) {
3310     FinalSize += sizeGlobalAddress(false);
3311   } else if (RelocOp->isCPI()) {
3312     FinalSize += sizeConstPoolAddress(false);
3313   } else if (RelocOp->isJTI()) {
3314     FinalSize += sizeJumpTableAddress(false);
3315   } else {
3316     llvm_unreachable("Unknown value to relocate!");
3317   }
3318   return FinalSize;
3319 }
3320
3321 static unsigned getMemModRMByteSize(const MachineInstr &MI, unsigned Op,
3322                                     bool IsPIC, bool Is64BitMode) {
3323   const MachineOperand &Op3 = MI.getOperand(Op+3);
3324   int DispVal = 0;
3325   const MachineOperand *DispForReloc = 0;
3326   unsigned FinalSize = 0;
3327   
3328   // Figure out what sort of displacement we have to handle here.
3329   if (Op3.isGlobal()) {
3330     DispForReloc = &Op3;
3331   } else if (Op3.isCPI()) {
3332     if (Is64BitMode || IsPIC) {
3333       DispForReloc = &Op3;
3334     } else {
3335       DispVal = 1;
3336     }
3337   } else if (Op3.isJTI()) {
3338     if (Is64BitMode || IsPIC) {
3339       DispForReloc = &Op3;
3340     } else {
3341       DispVal = 1; 
3342     }
3343   } else {
3344     DispVal = 1;
3345   }
3346
3347   const MachineOperand &Base     = MI.getOperand(Op);
3348   const MachineOperand &IndexReg = MI.getOperand(Op+2);
3349
3350   unsigned BaseReg = Base.getReg();
3351
3352   // Is a SIB byte needed?
3353   if ((!Is64BitMode || DispForReloc || BaseReg != 0) &&
3354       IndexReg.getReg() == 0 &&
3355       (BaseReg == 0 || X86RegisterInfo::getX86RegNum(BaseReg) != N86::ESP)) {      
3356     if (BaseReg == 0) {  // Just a displacement?
3357       // Emit special case [disp32] encoding
3358       ++FinalSize; 
3359       FinalSize += getDisplacementFieldSize(DispForReloc);
3360     } else {
3361       unsigned BaseRegNo = X86RegisterInfo::getX86RegNum(BaseReg);
3362       if (!DispForReloc && DispVal == 0 && BaseRegNo != N86::EBP) {
3363         // Emit simple indirect register encoding... [EAX] f.e.
3364         ++FinalSize;
3365       // Be pessimistic and assume it's a disp32, not a disp8
3366       } else {
3367         // Emit the most general non-SIB encoding: [REG+disp32]
3368         ++FinalSize;
3369         FinalSize += getDisplacementFieldSize(DispForReloc);
3370       }
3371     }
3372
3373   } else {  // We need a SIB byte, so start by outputting the ModR/M byte first
3374     assert(IndexReg.getReg() != X86::ESP &&
3375            IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
3376
3377     bool ForceDisp32 = false;
3378     if (BaseReg == 0 || DispForReloc) {
3379       // Emit the normal disp32 encoding.
3380       ++FinalSize;
3381       ForceDisp32 = true;
3382     } else {
3383       ++FinalSize;
3384     }
3385
3386     FinalSize += sizeSIBByte();
3387
3388     // Do we need to output a displacement?
3389     if (DispVal != 0 || ForceDisp32) {
3390       FinalSize += getDisplacementFieldSize(DispForReloc);
3391     }
3392   }
3393   return FinalSize;
3394 }
3395
3396
3397 static unsigned GetInstSizeWithDesc(const MachineInstr &MI,
3398                                     const TargetInstrDesc *Desc,
3399                                     bool IsPIC, bool Is64BitMode) {
3400   
3401   unsigned Opcode = Desc->Opcode;
3402   unsigned FinalSize = 0;
3403
3404   // Emit the lock opcode prefix as needed.
3405   if (Desc->TSFlags & X86II::LOCK) ++FinalSize;
3406
3407   // Emit segment override opcode prefix as needed.
3408   switch (Desc->TSFlags & X86II::SegOvrMask) {
3409   case X86II::FS:
3410   case X86II::GS:
3411    ++FinalSize;
3412    break;
3413   default: llvm_unreachable("Invalid segment!");
3414   case 0: break;  // No segment override!
3415   }
3416
3417   // Emit the repeat opcode prefix as needed.
3418   if ((Desc->TSFlags & X86II::Op0Mask) == X86II::REP) ++FinalSize;
3419
3420   // Emit the operand size opcode prefix as needed.
3421   if (Desc->TSFlags & X86II::OpSize) ++FinalSize;
3422
3423   // Emit the address size opcode prefix as needed.
3424   if (Desc->TSFlags & X86II::AdSize) ++FinalSize;
3425
3426   bool Need0FPrefix = false;
3427   switch (Desc->TSFlags & X86II::Op0Mask) {
3428   case X86II::TB:  // Two-byte opcode prefix
3429   case X86II::T8:  // 0F 38
3430   case X86II::TA:  // 0F 3A
3431     Need0FPrefix = true;
3432     break;
3433   case X86II::TF: // F2 0F 38
3434     ++FinalSize;
3435     Need0FPrefix = true;
3436     break;
3437   case X86II::REP: break; // already handled.
3438   case X86II::XS:   // F3 0F
3439     ++FinalSize;
3440     Need0FPrefix = true;
3441     break;
3442   case X86II::XD:   // F2 0F
3443     ++FinalSize;
3444     Need0FPrefix = true;
3445     break;
3446   case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
3447   case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
3448     ++FinalSize;
3449     break; // Two-byte opcode prefix
3450   default: llvm_unreachable("Invalid prefix!");
3451   case 0: break;  // No prefix!
3452   }
3453
3454   if (Is64BitMode) {
3455     // REX prefix
3456     unsigned REX = X86InstrInfo::determineREX(MI);
3457     if (REX)
3458       ++FinalSize;
3459   }
3460
3461   // 0x0F escape code must be emitted just before the opcode.
3462   if (Need0FPrefix)
3463     ++FinalSize;
3464
3465   switch (Desc->TSFlags & X86II::Op0Mask) {
3466   case X86II::T8:  // 0F 38
3467     ++FinalSize;
3468     break;
3469   case X86II::TA:  // 0F 3A
3470     ++FinalSize;
3471     break;
3472   case X86II::TF: // F2 0F 38
3473     ++FinalSize;
3474     break;
3475   }
3476
3477   // If this is a two-address instruction, skip one of the register operands.
3478   unsigned NumOps = Desc->getNumOperands();
3479   unsigned CurOp = 0;
3480   if (NumOps > 1 && Desc->getOperandConstraint(1, TOI::TIED_TO) != -1)
3481     CurOp++;
3482   else if (NumOps > 2 && Desc->getOperandConstraint(NumOps-1, TOI::TIED_TO)== 0)
3483     // Skip the last source operand that is tied_to the dest reg. e.g. LXADD32
3484     --NumOps;
3485
3486   switch (Desc->TSFlags & X86II::FormMask) {
3487   default: llvm_unreachable("Unknown FormMask value in X86 MachineCodeEmitter!");
3488   case X86II::Pseudo:
3489     // Remember the current PC offset, this is the PIC relocation
3490     // base address.
3491     switch (Opcode) {
3492     default: 
3493       break;
3494     case TargetOpcode::INLINEASM: {
3495       const MachineFunction *MF = MI.getParent()->getParent();
3496       const TargetInstrInfo &TII = *MF->getTarget().getInstrInfo();
3497       FinalSize += TII.getInlineAsmLength(MI.getOperand(0).getSymbolName(),
3498                                           *MF->getTarget().getMCAsmInfo());
3499       break;
3500     }
3501     case TargetOpcode::DBG_LABEL:
3502     case TargetOpcode::EH_LABEL:
3503     case TargetOpcode::DBG_VALUE:
3504       break;
3505     case TargetOpcode::IMPLICIT_DEF:
3506     case TargetOpcode::KILL:
3507     case X86::FP_REG_KILL:
3508       break;
3509     case X86::MOVPC32r: {
3510       // This emits the "call" portion of this pseudo instruction.
3511       ++FinalSize;
3512       FinalSize += sizeConstant(X86II::getSizeOfImm(Desc->TSFlags));
3513       break;
3514     }
3515     }
3516     CurOp = NumOps;
3517     break;
3518   case X86II::RawFrm:
3519     ++FinalSize;
3520
3521     if (CurOp != NumOps) {
3522       const MachineOperand &MO = MI.getOperand(CurOp++);
3523       if (MO.isMBB()) {
3524         FinalSize += sizePCRelativeBlockAddress();
3525       } else if (MO.isGlobal()) {
3526         FinalSize += sizeGlobalAddress(false);
3527       } else if (MO.isSymbol()) {
3528         FinalSize += sizeExternalSymbolAddress(false);
3529       } else if (MO.isImm()) {
3530         FinalSize += sizeConstant(X86II::getSizeOfImm(Desc->TSFlags));
3531       } else {
3532         llvm_unreachable("Unknown RawFrm operand!");
3533       }
3534     }
3535     break;
3536
3537   case X86II::AddRegFrm:
3538     ++FinalSize;
3539     ++CurOp;
3540     
3541     if (CurOp != NumOps) {
3542       const MachineOperand &MO1 = MI.getOperand(CurOp++);
3543       unsigned Size = X86II::getSizeOfImm(Desc->TSFlags);
3544       if (MO1.isImm())
3545         FinalSize += sizeConstant(Size);
3546       else {
3547         bool dword = false;
3548         if (Opcode == X86::MOV64ri)
3549           dword = true; 
3550         if (MO1.isGlobal()) {
3551           FinalSize += sizeGlobalAddress(dword);
3552         } else if (MO1.isSymbol())
3553           FinalSize += sizeExternalSymbolAddress(dword);
3554         else if (MO1.isCPI())
3555           FinalSize += sizeConstPoolAddress(dword);
3556         else if (MO1.isJTI())
3557           FinalSize += sizeJumpTableAddress(dword);
3558       }
3559     }
3560     break;
3561
3562   case X86II::MRMDestReg: {
3563     ++FinalSize; 
3564     FinalSize += sizeRegModRMByte();
3565     CurOp += 2;
3566     if (CurOp != NumOps) {
3567       ++CurOp;
3568       FinalSize += sizeConstant(X86II::getSizeOfImm(Desc->TSFlags));
3569     }
3570     break;
3571   }
3572   case X86II::MRMDestMem: {
3573     ++FinalSize;
3574     FinalSize += getMemModRMByteSize(MI, CurOp, IsPIC, Is64BitMode);
3575     CurOp +=  X86::AddrNumOperands + 1;
3576     if (CurOp != NumOps) {
3577       ++CurOp;
3578       FinalSize += sizeConstant(X86II::getSizeOfImm(Desc->TSFlags));
3579     }
3580     break;
3581   }
3582
3583   case X86II::MRMSrcReg:
3584     ++FinalSize;
3585     FinalSize += sizeRegModRMByte();
3586     CurOp += 2;
3587     if (CurOp != NumOps) {
3588       ++CurOp;
3589       FinalSize += sizeConstant(X86II::getSizeOfImm(Desc->TSFlags));
3590     }
3591     break;
3592
3593   case X86II::MRMSrcMem: {
3594     ++FinalSize;
3595     FinalSize += getMemModRMByteSize(MI, CurOp+1, IsPIC, Is64BitMode);
3596     CurOp += X86::AddrNumOperands + 1;
3597     if (CurOp != NumOps) {
3598       ++CurOp;
3599       FinalSize += sizeConstant(X86II::getSizeOfImm(Desc->TSFlags));
3600     }
3601     break;
3602   }
3603
3604   case X86II::MRM0r: case X86II::MRM1r:
3605   case X86II::MRM2r: case X86II::MRM3r:
3606   case X86II::MRM4r: case X86II::MRM5r:
3607   case X86II::MRM6r: case X86II::MRM7r:
3608     ++FinalSize;
3609     if (Desc->getOpcode() == X86::LFENCE ||
3610         Desc->getOpcode() == X86::MFENCE) {
3611       // Special handling of lfence and mfence;
3612       FinalSize += sizeRegModRMByte();
3613     } else if (Desc->getOpcode() == X86::MONITOR ||
3614                Desc->getOpcode() == X86::MWAIT) {
3615       // Special handling of monitor and mwait.
3616       FinalSize += sizeRegModRMByte() + 1; // +1 for the opcode.
3617     } else {
3618       ++CurOp;
3619       FinalSize += sizeRegModRMByte();
3620     }
3621
3622     if (CurOp != NumOps) {
3623       const MachineOperand &MO1 = MI.getOperand(CurOp++);
3624       unsigned Size = X86II::getSizeOfImm(Desc->TSFlags);
3625       if (MO1.isImm())
3626         FinalSize += sizeConstant(Size);
3627       else {
3628         bool dword = false;
3629         if (Opcode == X86::MOV64ri32)
3630           dword = true;
3631         if (MO1.isGlobal()) {
3632           FinalSize += sizeGlobalAddress(dword);
3633         } else if (MO1.isSymbol())
3634           FinalSize += sizeExternalSymbolAddress(dword);
3635         else if (MO1.isCPI())
3636           FinalSize += sizeConstPoolAddress(dword);
3637         else if (MO1.isJTI())
3638           FinalSize += sizeJumpTableAddress(dword);
3639       }
3640     }
3641     break;
3642
3643   case X86II::MRM0m: case X86II::MRM1m:
3644   case X86II::MRM2m: case X86II::MRM3m:
3645   case X86II::MRM4m: case X86II::MRM5m:
3646   case X86II::MRM6m: case X86II::MRM7m: {
3647     
3648     ++FinalSize;
3649     FinalSize += getMemModRMByteSize(MI, CurOp, IsPIC, Is64BitMode);
3650     CurOp += X86::AddrNumOperands;
3651
3652     if (CurOp != NumOps) {
3653       const MachineOperand &MO = MI.getOperand(CurOp++);
3654       unsigned Size = X86II::getSizeOfImm(Desc->TSFlags);
3655       if (MO.isImm())
3656         FinalSize += sizeConstant(Size);
3657       else {
3658         bool dword = false;
3659         if (Opcode == X86::MOV64mi32)
3660           dword = true;
3661         if (MO.isGlobal()) {
3662           FinalSize += sizeGlobalAddress(dword);
3663         } else if (MO.isSymbol())
3664           FinalSize += sizeExternalSymbolAddress(dword);
3665         else if (MO.isCPI())
3666           FinalSize += sizeConstPoolAddress(dword);
3667         else if (MO.isJTI())
3668           FinalSize += sizeJumpTableAddress(dword);
3669       }
3670     }
3671     break;
3672     
3673   case X86II::MRM_C1:
3674   case X86II::MRM_C8:
3675   case X86II::MRM_C9:
3676   case X86II::MRM_E8:
3677   case X86II::MRM_F0:
3678     FinalSize += 2;
3679     break;
3680   }
3681
3682   case X86II::MRMInitReg:
3683     ++FinalSize;
3684     // Duplicate register, used by things like MOV8r0 (aka xor reg,reg).
3685     FinalSize += sizeRegModRMByte();
3686     ++CurOp;
3687     break;
3688   }
3689
3690   if (!Desc->isVariadic() && CurOp != NumOps) {
3691     std::string msg;
3692     raw_string_ostream Msg(msg);
3693     Msg << "Cannot determine size: " << MI;
3694     report_fatal_error(Msg.str());
3695   }
3696   
3697
3698   return FinalSize;
3699 }
3700
3701
3702 unsigned X86InstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
3703   const TargetInstrDesc &Desc = MI->getDesc();
3704   bool IsPIC = TM.getRelocationModel() == Reloc::PIC_;
3705   bool Is64BitMode = TM.getSubtargetImpl()->is64Bit();
3706   unsigned Size = GetInstSizeWithDesc(*MI, &Desc, IsPIC, Is64BitMode);
3707   if (Desc.getOpcode() == X86::MOVPC32r)
3708     Size += GetInstSizeWithDesc(*MI, &get(X86::POP32r), IsPIC, Is64BitMode);
3709   return Size;
3710 }
3711
3712 /// getGlobalBaseReg - Return a virtual register initialized with the
3713 /// the global base register value. Output instructions required to
3714 /// initialize the register in the function entry block, if necessary.
3715 ///
3716 unsigned X86InstrInfo::getGlobalBaseReg(MachineFunction *MF) const {
3717   assert(!TM.getSubtarget<X86Subtarget>().is64Bit() &&
3718          "X86-64 PIC uses RIP relative addressing");
3719
3720   X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
3721   unsigned GlobalBaseReg = X86FI->getGlobalBaseReg();
3722   if (GlobalBaseReg != 0)
3723     return GlobalBaseReg;
3724
3725   // Insert the set of GlobalBaseReg into the first MBB of the function
3726   MachineBasicBlock &FirstMBB = MF->front();
3727   MachineBasicBlock::iterator MBBI = FirstMBB.begin();
3728   DebugLoc DL = FirstMBB.findDebugLoc(MBBI);
3729   MachineRegisterInfo &RegInfo = MF->getRegInfo();
3730   unsigned PC = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
3731   
3732   const TargetInstrInfo *TII = TM.getInstrInfo();
3733   // Operand of MovePCtoStack is completely ignored by asm printer. It's
3734   // only used in JIT code emission as displacement to pc.
3735   BuildMI(FirstMBB, MBBI, DL, TII->get(X86::MOVPC32r), PC).addImm(0);
3736   
3737   // If we're using vanilla 'GOT' PIC style, we should use relative addressing
3738   // not to pc, but to _GLOBAL_OFFSET_TABLE_ external.
3739   if (TM.getSubtarget<X86Subtarget>().isPICStyleGOT()) {
3740     GlobalBaseReg = RegInfo.createVirtualRegister(X86::GR32RegisterClass);
3741     // Generate addl $__GLOBAL_OFFSET_TABLE_ + [.-piclabel], %some_register
3742     BuildMI(FirstMBB, MBBI, DL, TII->get(X86::ADD32ri), GlobalBaseReg)
3743       .addReg(PC).addExternalSymbol("_GLOBAL_OFFSET_TABLE_",
3744                                     X86II::MO_GOT_ABSOLUTE_ADDRESS);
3745   } else {
3746     GlobalBaseReg = PC;
3747   }
3748
3749   X86FI->setGlobalBaseReg(GlobalBaseReg);
3750   return GlobalBaseReg;
3751 }
3752
3753 // These are the replaceable SSE instructions. Some of these have Int variants
3754 // that we don't include here. We don't want to replace instructions selected
3755 // by intrinsics.
3756 static const unsigned ReplaceableInstrs[][3] = {
3757   //PackedInt       PackedSingle     PackedDouble
3758   { X86::MOVAPSmr,   X86::MOVAPDmr,  X86::MOVDQAmr  },
3759   { X86::MOVAPSrm,   X86::MOVAPDrm,  X86::MOVDQArm  },
3760   { X86::MOVAPSrr,   X86::MOVAPDrr,  X86::MOVDQArr  },
3761   { X86::MOVUPSmr,   X86::MOVUPDmr,  X86::MOVDQUmr  },
3762   { X86::MOVUPSrm,   X86::MOVUPDrm,  X86::MOVDQUrm  },
3763   { X86::MOVNTPSmr,  X86::MOVNTPDmr, X86::MOVNTDQmr },
3764   { X86::ANDNPSrm,   X86::ANDNPDrm,  X86::PANDNrm   },
3765   { X86::ANDNPSrr,   X86::ANDNPDrr,  X86::PANDNrr   },
3766   { X86::ANDPSrm,    X86::ANDPDrm,   X86::PANDrm    },
3767   { X86::ANDPSrr,    X86::ANDPDrr,   X86::PANDrr    },
3768   { X86::ORPSrm,     X86::ORPDrm,    X86::PORrm     },
3769   { X86::ORPSrr,     X86::ORPDrr,    X86::PORrr     },
3770   { X86::V_SET0PS,   X86::V_SET0PD,  X86::V_SET0PI  },
3771   { X86::XORPSrm,    X86::XORPDrm,   X86::PXORrm    },
3772   { X86::XORPSrr,    X86::XORPDrr,   X86::PXORrr    },
3773 };
3774
3775 // FIXME: Some shuffle and unpack instructions have equivalents in different
3776 // domains, but they require a bit more work than just switching opcodes.
3777
3778 static const unsigned *lookup(unsigned opcode, unsigned domain) {
3779   for (unsigned i = 0, e = array_lengthof(ReplaceableInstrs); i != e; ++i)
3780     if (ReplaceableInstrs[i][domain-1] == opcode)
3781       return ReplaceableInstrs[i];
3782   return 0;
3783 }
3784
3785 std::pair<uint16_t, uint16_t>
3786 X86InstrInfo::GetSSEDomain(const MachineInstr *MI) const {
3787   uint16_t domain = (MI->getDesc().TSFlags >> X86II::SSEDomainShift) & 3;
3788   return std::make_pair(domain,
3789                         domain && lookup(MI->getOpcode(), domain) ? 0xe : 0);
3790 }
3791
3792 void X86InstrInfo::SetSSEDomain(MachineInstr *MI, unsigned Domain) const {
3793   assert(Domain>0 && Domain<4 && "Invalid execution domain");
3794   uint16_t dom = (MI->getDesc().TSFlags >> X86II::SSEDomainShift) & 3;
3795   assert(dom && "Not an SSE instruction");
3796   const unsigned *table = lookup(MI->getOpcode(), dom);
3797   assert(table && "Cannot change domain");
3798   MI->setDesc(get(table[Domain-1]));
3799 }
3800
3801 /// getNoopForMachoTarget - Return the noop instruction to use for a noop.
3802 void X86InstrInfo::getNoopForMachoTarget(MCInst &NopInst) const {
3803   NopInst.setOpcode(X86::NOOP);
3804 }