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