blob: 9d817164b05367d569c3b5b95889a29794a39037 [file] [log] [blame]
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001//===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
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 defines the X86-specific support for the FastISel class. Much
11// of the target-specific code is generated by tablegen in the file
12// X86GenFastISel.inc, which is #included here.
13//
14//===----------------------------------------------------------------------===//
15
16#include "X86.h"
17#include "X86CallingConv.h"
18#include "X86InstrBuilder.h"
19#include "X86InstrInfo.h"
20#include "X86MachineFunctionInfo.h"
21#include "X86RegisterInfo.h"
22#include "X86Subtarget.h"
23#include "X86TargetMachine.h"
24#include "llvm/Analysis/BranchProbabilityInfo.h"
25#include "llvm/CodeGen/Analysis.h"
26#include "llvm/CodeGen/FastISel.h"
27#include "llvm/CodeGen/FunctionLoweringInfo.h"
28#include "llvm/CodeGen/MachineConstantPool.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineRegisterInfo.h"
31#include "llvm/IR/CallSite.h"
32#include "llvm/IR/CallingConv.h"
33#include "llvm/IR/DerivedTypes.h"
34#include "llvm/IR/GetElementPtrTypeIterator.h"
35#include "llvm/IR/GlobalAlias.h"
36#include "llvm/IR/GlobalVariable.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/Operator.h"
David Majnemerca194852015-02-10 22:00:34 +000040#include "llvm/MC/MCAsmInfo.h"
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000041#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Target/TargetOptions.h"
43using namespace llvm;
44
45namespace {
46
47class X86FastISel final : public FastISel {
48 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
49 /// make the right decision when generating code for different targets.
50 const X86Subtarget *Subtarget;
51
52 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
53 /// floating point ops.
54 /// When SSE is available, use it for f32 operations.
55 /// When SSE2 is available, use it for f64 operations.
56 bool X86ScalarSSEf64;
57 bool X86ScalarSSEf32;
58
59public:
60 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
61 const TargetLibraryInfo *libInfo)
Eric Christophera1c535b2015-02-02 23:03:45 +000062 : FastISel(funcInfo, libInfo) {
63 Subtarget = &funcInfo.MF->getSubtarget<X86Subtarget>();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000064 X86ScalarSSEf64 = Subtarget->hasSSE2();
65 X86ScalarSSEf32 = Subtarget->hasSSE1();
66 }
67
68 bool fastSelectInstruction(const Instruction *I) override;
69
70 /// \brief The specified machine instr operand is a vreg, and that
71 /// vreg is being provided by the specified load instruction. If possible,
72 /// try to fold the load as an operand to the instruction, returning true if
73 /// possible.
74 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
75 const LoadInst *LI) override;
76
77 bool fastLowerArguments() override;
78 bool fastLowerCall(CallLoweringInfo &CLI) override;
79 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
80
81#include "X86GenFastISel.inc"
82
83private:
84 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT, DebugLoc DL);
85
Pete Cooperd0dae3e2015-05-05 23:41:53 +000086 bool X86FastEmitLoad(EVT VT, X86AddressMode &AM, MachineMemOperand *MMO,
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +000087 unsigned &ResultReg, unsigned Alignment = 1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000088
Pete Cooperd0dae3e2015-05-05 23:41:53 +000089 bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000090 MachineMemOperand *MMO = nullptr, bool Aligned = false);
91 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
Pete Cooperd0dae3e2015-05-05 23:41:53 +000092 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000093 MachineMemOperand *MMO = nullptr, bool Aligned = false);
94
95 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
96 unsigned &ResultReg);
97
98 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
99 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
100
101 bool X86SelectLoad(const Instruction *I);
102
103 bool X86SelectStore(const Instruction *I);
104
105 bool X86SelectRet(const Instruction *I);
106
107 bool X86SelectCmp(const Instruction *I);
108
109 bool X86SelectZExt(const Instruction *I);
110
111 bool X86SelectBranch(const Instruction *I);
112
113 bool X86SelectShift(const Instruction *I);
114
115 bool X86SelectDivRem(const Instruction *I);
116
117 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
118
119 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
120
121 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
122
123 bool X86SelectSelect(const Instruction *I);
124
125 bool X86SelectTrunc(const Instruction *I);
126
Andrea Di Biagio62622d22015-02-10 12:04:41 +0000127 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
128 const TargetRegisterClass *RC);
129
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000130 bool X86SelectFPExt(const Instruction *I);
131 bool X86SelectFPTrunc(const Instruction *I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +0000132 bool X86SelectSIToFP(const Instruction *I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000133
134 const X86InstrInfo *getInstrInfo() const {
Eric Christophera1c535b2015-02-02 23:03:45 +0000135 return Subtarget->getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000136 }
137 const X86TargetMachine *getTargetMachine() const {
138 return static_cast<const X86TargetMachine *>(&TM);
139 }
140
141 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
142
143 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
144 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
145 unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
146 unsigned fastMaterializeConstant(const Constant *C) override;
147
148 unsigned fastMaterializeAlloca(const AllocaInst *C) override;
149
150 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
151
152 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
153 /// computed in an SSE register, not on the X87 floating point stack.
154 bool isScalarFPTypeInSSEReg(EVT VT) const {
155 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
156 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
157 }
158
159 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
160
161 bool IsMemcpySmall(uint64_t Len);
162
163 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
164 X86AddressMode SrcAM, uint64_t Len);
165
166 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
167 const Value *Cond);
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000168
169 const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB,
170 X86AddressMode &AM);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000171};
172
173} // end anonymous namespace.
174
175static std::pair<X86::CondCode, bool>
176getX86ConditionCode(CmpInst::Predicate Predicate) {
177 X86::CondCode CC = X86::COND_INVALID;
178 bool NeedSwap = false;
179 switch (Predicate) {
180 default: break;
181 // Floating-point Predicates
182 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
183 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
184 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
185 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
186 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
187 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
188 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
189 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
190 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
191 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
192 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
193 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
194 case CmpInst::FCMP_OEQ: // fall-through
195 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
196
197 // Integer Predicates
198 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
199 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
200 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
201 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
202 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
203 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
204 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
205 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
206 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
207 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
208 }
209
210 return std::make_pair(CC, NeedSwap);
211}
212
213static std::pair<unsigned, bool>
214getX86SSEConditionCode(CmpInst::Predicate Predicate) {
215 unsigned CC;
216 bool NeedSwap = false;
217
218 // SSE Condition code mapping:
219 // 0 - EQ
220 // 1 - LT
221 // 2 - LE
222 // 3 - UNORD
223 // 4 - NEQ
224 // 5 - NLT
225 // 6 - NLE
226 // 7 - ORD
227 switch (Predicate) {
228 default: llvm_unreachable("Unexpected predicate");
229 case CmpInst::FCMP_OEQ: CC = 0; break;
230 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through
231 case CmpInst::FCMP_OLT: CC = 1; break;
232 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through
233 case CmpInst::FCMP_OLE: CC = 2; break;
234 case CmpInst::FCMP_UNO: CC = 3; break;
235 case CmpInst::FCMP_UNE: CC = 4; break;
236 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through
237 case CmpInst::FCMP_UGE: CC = 5; break;
238 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through
239 case CmpInst::FCMP_UGT: CC = 6; break;
240 case CmpInst::FCMP_ORD: CC = 7; break;
241 case CmpInst::FCMP_UEQ:
242 case CmpInst::FCMP_ONE: CC = 8; break;
243 }
244
245 return std::make_pair(CC, NeedSwap);
246}
247
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000248/// \brief Adds a complex addressing mode to the given machine instr builder.
249/// Note, this will constrain the index register. If its not possible to
250/// constrain the given index register, then a new one will be created. The
251/// IndexReg field of the addressing mode will be updated to match in this case.
252const MachineInstrBuilder &
253X86FastISel::addFullAddress(const MachineInstrBuilder &MIB,
254 X86AddressMode &AM) {
255 // First constrain the index register. It needs to be a GR64_NOSP.
256 AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg,
257 MIB->getNumOperands() +
258 X86::AddrIndexReg);
259 return ::addFullAddress(MIB, AM);
260}
261
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000262/// \brief Check if it is possible to fold the condition from the XALU intrinsic
263/// into the user. The condition code will only be updated on success.
264bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
265 const Value *Cond) {
266 if (!isa<ExtractValueInst>(Cond))
267 return false;
268
269 const auto *EV = cast<ExtractValueInst>(Cond);
270 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
271 return false;
272
273 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
274 MVT RetVT;
275 const Function *Callee = II->getCalledFunction();
276 Type *RetTy =
277 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
278 if (!isTypeLegal(RetTy, RetVT))
279 return false;
280
281 if (RetVT != MVT::i32 && RetVT != MVT::i64)
282 return false;
283
284 X86::CondCode TmpCC;
285 switch (II->getIntrinsicID()) {
286 default: return false;
287 case Intrinsic::sadd_with_overflow:
288 case Intrinsic::ssub_with_overflow:
289 case Intrinsic::smul_with_overflow:
290 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
291 case Intrinsic::uadd_with_overflow:
292 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
293 }
294
295 // Check if both instructions are in the same basic block.
296 if (II->getParent() != I->getParent())
297 return false;
298
299 // Make sure nothing is in the way
300 BasicBlock::const_iterator Start = I;
301 BasicBlock::const_iterator End = II;
302 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
303 // We only expect extractvalue instructions between the intrinsic and the
304 // instruction to be selected.
305 if (!isa<ExtractValueInst>(Itr))
306 return false;
307
308 // Check that the extractvalue operand comes from the intrinsic.
309 const auto *EVI = cast<ExtractValueInst>(Itr);
310 if (EVI->getAggregateOperand() != II)
311 return false;
312 }
313
314 CC = TmpCC;
315 return true;
316}
317
318bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
319 EVT evt = TLI.getValueType(Ty, /*HandleUnknown=*/true);
320 if (evt == MVT::Other || !evt.isSimple())
321 // Unhandled type. Halt "fast" selection and bail.
322 return false;
323
324 VT = evt.getSimpleVT();
325 // For now, require SSE/SSE2 for performing floating-point operations,
326 // since x87 requires additional work.
327 if (VT == MVT::f64 && !X86ScalarSSEf64)
328 return false;
329 if (VT == MVT::f32 && !X86ScalarSSEf32)
330 return false;
331 // Similarly, no f80 support yet.
332 if (VT == MVT::f80)
333 return false;
334 // We only handle legal types. For example, on x86-32 the instruction
335 // selector contains all of the 64-bit instructions from x86-64,
336 // under the assumption that i64 won't be used if the target doesn't
337 // support it.
338 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
339}
340
341#include "X86GenCallingConv.inc"
342
343/// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
344/// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
345/// Return true and the result register by reference if it is possible.
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000346bool X86FastISel::X86FastEmitLoad(EVT VT, X86AddressMode &AM,
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000347 MachineMemOperand *MMO, unsigned &ResultReg,
348 unsigned Alignment) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000349 // Get opcode and regclass of the output for the given load instruction.
350 unsigned Opc = 0;
351 const TargetRegisterClass *RC = nullptr;
352 switch (VT.getSimpleVT().SimpleTy) {
353 default: return false;
354 case MVT::i1:
355 case MVT::i8:
356 Opc = X86::MOV8rm;
357 RC = &X86::GR8RegClass;
358 break;
359 case MVT::i16:
360 Opc = X86::MOV16rm;
361 RC = &X86::GR16RegClass;
362 break;
363 case MVT::i32:
364 Opc = X86::MOV32rm;
365 RC = &X86::GR32RegClass;
366 break;
367 case MVT::i64:
368 // Must be in x86-64 mode.
369 Opc = X86::MOV64rm;
370 RC = &X86::GR64RegClass;
371 break;
372 case MVT::f32:
373 if (X86ScalarSSEf32) {
374 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
375 RC = &X86::FR32RegClass;
376 } else {
377 Opc = X86::LD_Fp32m;
378 RC = &X86::RFP32RegClass;
379 }
380 break;
381 case MVT::f64:
382 if (X86ScalarSSEf64) {
383 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
384 RC = &X86::FR64RegClass;
385 } else {
386 Opc = X86::LD_Fp64m;
387 RC = &X86::RFP64RegClass;
388 }
389 break;
390 case MVT::f80:
391 // No f80 support yet.
392 return false;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000393 case MVT::v4f32:
394 if (Alignment >= 16)
395 Opc = Subtarget->hasAVX() ? X86::VMOVAPSrm : X86::MOVAPSrm;
396 else
397 Opc = Subtarget->hasAVX() ? X86::VMOVUPSrm : X86::MOVUPSrm;
398 RC = &X86::VR128RegClass;
399 break;
400 case MVT::v2f64:
401 if (Alignment >= 16)
402 Opc = Subtarget->hasAVX() ? X86::VMOVAPDrm : X86::MOVAPDrm;
403 else
404 Opc = Subtarget->hasAVX() ? X86::VMOVUPDrm : X86::MOVUPDrm;
405 RC = &X86::VR128RegClass;
406 break;
407 case MVT::v4i32:
408 case MVT::v2i64:
409 case MVT::v8i16:
410 case MVT::v16i8:
411 if (Alignment >= 16)
412 Opc = Subtarget->hasAVX() ? X86::VMOVDQArm : X86::MOVDQArm;
413 else
414 Opc = Subtarget->hasAVX() ? X86::VMOVDQUrm : X86::MOVDQUrm;
415 RC = &X86::VR128RegClass;
416 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000417 }
418
419 ResultReg = createResultReg(RC);
420 MachineInstrBuilder MIB =
421 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
422 addFullAddress(MIB, AM);
423 if (MMO)
424 MIB->addMemOperand(*FuncInfo.MF, MMO);
425 return true;
426}
427
428/// X86FastEmitStore - Emit a machine instruction to store a value Val of
429/// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
430/// and a displacement offset, or a GlobalAddress,
431/// i.e. V. Return true if it is possible.
432bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000433 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000434 MachineMemOperand *MMO, bool Aligned) {
435 // Get opcode and regclass of the output for the given store instruction.
436 unsigned Opc = 0;
437 switch (VT.getSimpleVT().SimpleTy) {
438 case MVT::f80: // No f80 support yet.
439 default: return false;
440 case MVT::i1: {
441 // Mask out all but lowest bit.
442 unsigned AndResult = createResultReg(&X86::GR8RegClass);
443 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
444 TII.get(X86::AND8ri), AndResult)
445 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
446 ValReg = AndResult;
447 }
448 // FALLTHROUGH, handling i1 as i8.
449 case MVT::i8: Opc = X86::MOV8mr; break;
450 case MVT::i16: Opc = X86::MOV16mr; break;
451 case MVT::i32: Opc = X86::MOV32mr; break;
452 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
453 case MVT::f32:
454 Opc = X86ScalarSSEf32 ?
455 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
456 break;
457 case MVT::f64:
458 Opc = X86ScalarSSEf64 ?
459 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
460 break;
461 case MVT::v4f32:
462 if (Aligned)
463 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
464 else
465 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
466 break;
467 case MVT::v2f64:
468 if (Aligned)
469 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
470 else
471 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
472 break;
473 case MVT::v4i32:
474 case MVT::v2i64:
475 case MVT::v8i16:
476 case MVT::v16i8:
477 if (Aligned)
478 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
479 else
480 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
481 break;
482 }
483
484 MachineInstrBuilder MIB =
485 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
486 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
487 if (MMO)
488 MIB->addMemOperand(*FuncInfo.MF, MMO);
489
490 return true;
491}
492
493bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000494 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000495 MachineMemOperand *MMO, bool Aligned) {
496 // Handle 'null' like i32/i64 0.
497 if (isa<ConstantPointerNull>(Val))
498 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
499
500 // If this is a store of a simple constant, fold the constant into the store.
501 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
502 unsigned Opc = 0;
503 bool Signed = true;
504 switch (VT.getSimpleVT().SimpleTy) {
505 default: break;
506 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
507 case MVT::i8: Opc = X86::MOV8mi; break;
508 case MVT::i16: Opc = X86::MOV16mi; break;
509 case MVT::i32: Opc = X86::MOV32mi; break;
510 case MVT::i64:
511 // Must be a 32-bit sign extended value.
512 if (isInt<32>(CI->getSExtValue()))
513 Opc = X86::MOV64mi32;
514 break;
515 }
516
517 if (Opc) {
518 MachineInstrBuilder MIB =
519 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
520 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
521 : CI->getZExtValue());
522 if (MMO)
523 MIB->addMemOperand(*FuncInfo.MF, MMO);
524 return true;
525 }
526 }
527
528 unsigned ValReg = getRegForValue(Val);
529 if (ValReg == 0)
530 return false;
531
532 bool ValKill = hasTrivialKill(Val);
533 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
534}
535
536/// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
537/// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
538/// ISD::SIGN_EXTEND).
539bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
540 unsigned Src, EVT SrcVT,
541 unsigned &ResultReg) {
542 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
543 Src, /*TODO: Kill=*/false);
544 if (RR == 0)
545 return false;
546
547 ResultReg = RR;
548 return true;
549}
550
551bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
552 // Handle constant address.
553 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
554 // Can't handle alternate code models yet.
555 if (TM.getCodeModel() != CodeModel::Small)
556 return false;
557
558 // Can't handle TLS yet.
559 if (GV->isThreadLocal())
560 return false;
561
562 // RIP-relative addresses can't have additional register operands, so if
563 // we've already folded stuff into the addressing mode, just force the
564 // global value into its own register, which we can use as the basereg.
565 if (!Subtarget->isPICStyleRIPRel() ||
566 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
567 // Okay, we've committed to selecting this global. Set up the address.
568 AM.GV = GV;
569
570 // Allow the subtarget to classify the global.
571 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
572
573 // If this reference is relative to the pic base, set it now.
574 if (isGlobalRelativeToPICBase(GVFlags)) {
575 // FIXME: How do we know Base.Reg is free??
576 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
577 }
578
579 // Unless the ABI requires an extra load, return a direct reference to
580 // the global.
581 if (!isGlobalStubReference(GVFlags)) {
582 if (Subtarget->isPICStyleRIPRel()) {
583 // Use rip-relative addressing if we can. Above we verified that the
584 // base and index registers are unused.
585 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
586 AM.Base.Reg = X86::RIP;
587 }
588 AM.GVOpFlags = GVFlags;
589 return true;
590 }
591
592 // Ok, we need to do a load from a stub. If we've already loaded from
593 // this stub, reuse the loaded pointer, otherwise emit the load now.
594 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
595 unsigned LoadReg;
596 if (I != LocalValueMap.end() && I->second != 0) {
597 LoadReg = I->second;
598 } else {
599 // Issue load from stub.
600 unsigned Opc = 0;
601 const TargetRegisterClass *RC = nullptr;
602 X86AddressMode StubAM;
603 StubAM.Base.Reg = AM.Base.Reg;
604 StubAM.GV = GV;
605 StubAM.GVOpFlags = GVFlags;
606
607 // Prepare for inserting code in the local-value area.
608 SavePoint SaveInsertPt = enterLocalValueArea();
609
610 if (TLI.getPointerTy() == MVT::i64) {
611 Opc = X86::MOV64rm;
612 RC = &X86::GR64RegClass;
613
614 if (Subtarget->isPICStyleRIPRel())
615 StubAM.Base.Reg = X86::RIP;
616 } else {
617 Opc = X86::MOV32rm;
618 RC = &X86::GR32RegClass;
619 }
620
621 LoadReg = createResultReg(RC);
622 MachineInstrBuilder LoadMI =
623 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
624 addFullAddress(LoadMI, StubAM);
625
626 // Ok, back to normal mode.
627 leaveLocalValueArea(SaveInsertPt);
628
629 // Prevent loading GV stub multiple times in same MBB.
630 LocalValueMap[V] = LoadReg;
631 }
632
633 // Now construct the final address. Note that the Disp, Scale,
634 // and Index values may already be set here.
635 AM.Base.Reg = LoadReg;
636 AM.GV = nullptr;
637 return true;
638 }
639 }
640
641 // If all else fails, try to materialize the value in a register.
642 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
643 if (AM.Base.Reg == 0) {
644 AM.Base.Reg = getRegForValue(V);
645 return AM.Base.Reg != 0;
646 }
647 if (AM.IndexReg == 0) {
648 assert(AM.Scale == 1 && "Scale with no index!");
649 AM.IndexReg = getRegForValue(V);
650 return AM.IndexReg != 0;
651 }
652 }
653
654 return false;
655}
656
657/// X86SelectAddress - Attempt to fill in an address from the given value.
658///
659bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
660 SmallVector<const Value *, 32> GEPs;
661redo_gep:
662 const User *U = nullptr;
663 unsigned Opcode = Instruction::UserOp1;
664 if (const Instruction *I = dyn_cast<Instruction>(V)) {
665 // Don't walk into other basic blocks; it's possible we haven't
666 // visited them yet, so the instructions may not yet be assigned
667 // virtual registers.
668 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
669 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
670 Opcode = I->getOpcode();
671 U = I;
672 }
673 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
674 Opcode = C->getOpcode();
675 U = C;
676 }
677
678 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
679 if (Ty->getAddressSpace() > 255)
680 // Fast instruction selection doesn't support the special
681 // address spaces.
682 return false;
683
684 switch (Opcode) {
685 default: break;
686 case Instruction::BitCast:
687 // Look past bitcasts.
688 return X86SelectAddress(U->getOperand(0), AM);
689
690 case Instruction::IntToPtr:
691 // Look past no-op inttoptrs.
692 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
693 return X86SelectAddress(U->getOperand(0), AM);
694 break;
695
696 case Instruction::PtrToInt:
697 // Look past no-op ptrtoints.
698 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
699 return X86SelectAddress(U->getOperand(0), AM);
700 break;
701
702 case Instruction::Alloca: {
703 // Do static allocas.
704 const AllocaInst *A = cast<AllocaInst>(V);
705 DenseMap<const AllocaInst *, int>::iterator SI =
706 FuncInfo.StaticAllocaMap.find(A);
707 if (SI != FuncInfo.StaticAllocaMap.end()) {
708 AM.BaseType = X86AddressMode::FrameIndexBase;
709 AM.Base.FrameIndex = SI->second;
710 return true;
711 }
712 break;
713 }
714
715 case Instruction::Add: {
716 // Adds of constants are common and easy enough.
717 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
718 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
719 // They have to fit in the 32-bit signed displacement field though.
720 if (isInt<32>(Disp)) {
721 AM.Disp = (uint32_t)Disp;
722 return X86SelectAddress(U->getOperand(0), AM);
723 }
724 }
725 break;
726 }
727
728 case Instruction::GetElementPtr: {
729 X86AddressMode SavedAM = AM;
730
731 // Pattern-match simple GEPs.
732 uint64_t Disp = (int32_t)AM.Disp;
733 unsigned IndexReg = AM.IndexReg;
734 unsigned Scale = AM.Scale;
735 gep_type_iterator GTI = gep_type_begin(U);
736 // Iterate through the indices, folding what we can. Constants can be
737 // folded, and one dynamic index can be handled, if the scale is supported.
738 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
739 i != e; ++i, ++GTI) {
740 const Value *Op = *i;
741 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
742 const StructLayout *SL = DL.getStructLayout(STy);
743 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
744 continue;
745 }
746
747 // A array/variable index is always of the form i*S where S is the
748 // constant scale size. See if we can push the scale into immediates.
749 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
750 for (;;) {
751 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
752 // Constant-offset addressing.
753 Disp += CI->getSExtValue() * S;
754 break;
755 }
756 if (canFoldAddIntoGEP(U, Op)) {
757 // A compatible add with a constant operand. Fold the constant.
758 ConstantInt *CI =
759 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
760 Disp += CI->getSExtValue() * S;
761 // Iterate on the other operand.
762 Op = cast<AddOperator>(Op)->getOperand(0);
763 continue;
764 }
765 if (IndexReg == 0 &&
766 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
767 (S == 1 || S == 2 || S == 4 || S == 8)) {
768 // Scaled-index addressing.
769 Scale = S;
770 IndexReg = getRegForGEPIndex(Op).first;
771 if (IndexReg == 0)
772 return false;
773 break;
774 }
775 // Unsupported.
776 goto unsupported_gep;
777 }
778 }
779
780 // Check for displacement overflow.
781 if (!isInt<32>(Disp))
782 break;
783
784 AM.IndexReg = IndexReg;
785 AM.Scale = Scale;
786 AM.Disp = (uint32_t)Disp;
787 GEPs.push_back(V);
788
789 if (const GetElementPtrInst *GEP =
790 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
791 // Ok, the GEP indices were covered by constant-offset and scaled-index
792 // addressing. Update the address state and move on to examining the base.
793 V = GEP;
794 goto redo_gep;
795 } else if (X86SelectAddress(U->getOperand(0), AM)) {
796 return true;
797 }
798
799 // If we couldn't merge the gep value into this addr mode, revert back to
800 // our address and just match the value instead of completely failing.
801 AM = SavedAM;
802
803 for (SmallVectorImpl<const Value *>::reverse_iterator
804 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
805 if (handleConstantAddresses(*I, AM))
806 return true;
807
808 return false;
809 unsupported_gep:
810 // Ok, the GEP indices weren't all covered.
811 break;
812 }
813 }
814
815 return handleConstantAddresses(V, AM);
816}
817
818/// X86SelectCallAddress - Attempt to fill in an address from the given value.
819///
820bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
821 const User *U = nullptr;
822 unsigned Opcode = Instruction::UserOp1;
823 const Instruction *I = dyn_cast<Instruction>(V);
824 // Record if the value is defined in the same basic block.
825 //
826 // This information is crucial to know whether or not folding an
827 // operand is valid.
828 // Indeed, FastISel generates or reuses a virtual register for all
829 // operands of all instructions it selects. Obviously, the definition and
830 // its uses must use the same virtual register otherwise the produced
831 // code is incorrect.
832 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
833 // registers for values that are alive across basic blocks. This ensures
834 // that the values are consistently set between across basic block, even
835 // if different instruction selection mechanisms are used (e.g., a mix of
836 // SDISel and FastISel).
837 // For values local to a basic block, the instruction selection process
838 // generates these virtual registers with whatever method is appropriate
839 // for its needs. In particular, FastISel and SDISel do not share the way
840 // local virtual registers are set.
841 // Therefore, this is impossible (or at least unsafe) to share values
842 // between basic blocks unless they use the same instruction selection
843 // method, which is not guarantee for X86.
844 // Moreover, things like hasOneUse could not be used accurately, if we
845 // allow to reference values across basic blocks whereas they are not
846 // alive across basic blocks initially.
847 bool InMBB = true;
848 if (I) {
849 Opcode = I->getOpcode();
850 U = I;
851 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
852 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
853 Opcode = C->getOpcode();
854 U = C;
855 }
856
857 switch (Opcode) {
858 default: break;
859 case Instruction::BitCast:
860 // Look past bitcasts if its operand is in the same BB.
861 if (InMBB)
862 return X86SelectCallAddress(U->getOperand(0), AM);
863 break;
864
865 case Instruction::IntToPtr:
866 // Look past no-op inttoptrs if its operand is in the same BB.
867 if (InMBB &&
868 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
869 return X86SelectCallAddress(U->getOperand(0), AM);
870 break;
871
872 case Instruction::PtrToInt:
873 // Look past no-op ptrtoints if its operand is in the same BB.
874 if (InMBB &&
875 TLI.getValueType(U->getType()) == TLI.getPointerTy())
876 return X86SelectCallAddress(U->getOperand(0), AM);
877 break;
878 }
879
880 // Handle constant address.
881 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
882 // Can't handle alternate code models yet.
883 if (TM.getCodeModel() != CodeModel::Small)
884 return false;
885
886 // RIP-relative addresses can't have additional register operands.
887 if (Subtarget->isPICStyleRIPRel() &&
888 (AM.Base.Reg != 0 || AM.IndexReg != 0))
889 return false;
890
891 // Can't handle DLL Import.
892 if (GV->hasDLLImportStorageClass())
893 return false;
894
895 // Can't handle TLS.
896 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
897 if (GVar->isThreadLocal())
898 return false;
899
900 // Okay, we've committed to selecting this global. Set up the basic address.
901 AM.GV = GV;
902
903 // No ABI requires an extra load for anything other than DLLImport, which
904 // we rejected above. Return a direct reference to the global.
905 if (Subtarget->isPICStyleRIPRel()) {
906 // Use rip-relative addressing if we can. Above we verified that the
907 // base and index registers are unused.
908 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
909 AM.Base.Reg = X86::RIP;
910 } else if (Subtarget->isPICStyleStubPIC()) {
911 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
912 } else if (Subtarget->isPICStyleGOT()) {
913 AM.GVOpFlags = X86II::MO_GOTOFF;
914 }
915
916 return true;
917 }
918
919 // If all else fails, try to materialize the value in a register.
920 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
921 if (AM.Base.Reg == 0) {
922 AM.Base.Reg = getRegForValue(V);
923 return AM.Base.Reg != 0;
924 }
925 if (AM.IndexReg == 0) {
926 assert(AM.Scale == 1 && "Scale with no index!");
927 AM.IndexReg = getRegForValue(V);
928 return AM.IndexReg != 0;
929 }
930 }
931
932 return false;
933}
934
935
936/// X86SelectStore - Select and emit code to implement store instructions.
937bool X86FastISel::X86SelectStore(const Instruction *I) {
938 // Atomic stores need special handling.
939 const StoreInst *S = cast<StoreInst>(I);
940
941 if (S->isAtomic())
942 return false;
943
944 const Value *Val = S->getValueOperand();
945 const Value *Ptr = S->getPointerOperand();
946
947 MVT VT;
948 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
949 return false;
950
951 unsigned Alignment = S->getAlignment();
952 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
953 if (Alignment == 0) // Ensure that codegen never sees alignment 0
954 Alignment = ABIAlignment;
955 bool Aligned = Alignment >= ABIAlignment;
956
957 X86AddressMode AM;
958 if (!X86SelectAddress(Ptr, AM))
959 return false;
960
961 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
962}
963
964/// X86SelectRet - Select and emit code to implement ret instructions.
965bool X86FastISel::X86SelectRet(const Instruction *I) {
966 const ReturnInst *Ret = cast<ReturnInst>(I);
967 const Function &F = *I->getParent()->getParent();
968 const X86MachineFunctionInfo *X86MFInfo =
969 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
970
971 if (!FuncInfo.CanLowerReturn)
972 return false;
973
974 CallingConv::ID CC = F.getCallingConv();
975 if (CC != CallingConv::C &&
976 CC != CallingConv::Fast &&
977 CC != CallingConv::X86_FastCall &&
978 CC != CallingConv::X86_64_SysV)
979 return false;
980
981 if (Subtarget->isCallingConvWin64(CC))
982 return false;
983
984 // Don't handle popping bytes on return for now.
985 if (X86MFInfo->getBytesToPopOnReturn() != 0)
986 return false;
987
988 // fastcc with -tailcallopt is intended to provide a guaranteed
989 // tail call optimization. Fastisel doesn't know how to do that.
990 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
991 return false;
992
993 // Let SDISel handle vararg functions.
994 if (F.isVarArg())
995 return false;
996
997 // Build a list of return value registers.
998 SmallVector<unsigned, 4> RetRegs;
999
1000 if (Ret->getNumOperands() > 0) {
1001 SmallVector<ISD::OutputArg, 4> Outs;
1002 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
1003
1004 // Analyze operands of the call, assigning locations to each operand.
1005 SmallVector<CCValAssign, 16> ValLocs;
1006 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1007 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1008
1009 const Value *RV = Ret->getOperand(0);
1010 unsigned Reg = getRegForValue(RV);
1011 if (Reg == 0)
1012 return false;
1013
1014 // Only handle a single return value for now.
1015 if (ValLocs.size() != 1)
1016 return false;
1017
1018 CCValAssign &VA = ValLocs[0];
1019
1020 // Don't bother handling odd stuff for now.
1021 if (VA.getLocInfo() != CCValAssign::Full)
1022 return false;
1023 // Only handle register returns for now.
1024 if (!VA.isRegLoc())
1025 return false;
1026
1027 // The calling-convention tables for x87 returns don't tell
1028 // the whole story.
1029 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1030 return false;
1031
1032 unsigned SrcReg = Reg + VA.getValNo();
1033 EVT SrcVT = TLI.getValueType(RV->getType());
1034 EVT DstVT = VA.getValVT();
1035 // Special handling for extended integers.
1036 if (SrcVT != DstVT) {
1037 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1038 return false;
1039
1040 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1041 return false;
1042
1043 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1044
1045 if (SrcVT == MVT::i1) {
1046 if (Outs[0].Flags.isSExt())
1047 return false;
1048 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1049 SrcVT = MVT::i8;
1050 }
1051 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1052 ISD::SIGN_EXTEND;
1053 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1054 SrcReg, /*TODO: Kill=*/false);
1055 }
1056
1057 // Make the copy.
1058 unsigned DstReg = VA.getLocReg();
1059 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1060 // Avoid a cross-class copy. This is very unlikely.
1061 if (!SrcRC->contains(DstReg))
1062 return false;
1063 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1064 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1065
1066 // Add register to return instruction.
1067 RetRegs.push_back(VA.getLocReg());
1068 }
1069
1070 // The x86-64 ABI for returning structs by value requires that we copy
1071 // the sret argument into %rax for the return. We saved the argument into
1072 // a virtual register in the entry block, so now we copy the value out
1073 // and into %rax. We also do the same with %eax for Win32.
1074 if (F.hasStructRetAttr() &&
1075 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1076 unsigned Reg = X86MFInfo->getSRetReturnReg();
1077 assert(Reg &&
1078 "SRetReturnReg should have been set in LowerFormalArguments()!");
1079 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1080 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1081 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1082 RetRegs.push_back(RetReg);
1083 }
1084
1085 // Now emit the RET.
1086 MachineInstrBuilder MIB =
1087 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1088 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1089 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1090 MIB.addReg(RetRegs[i], RegState::Implicit);
1091 return true;
1092}
1093
1094/// X86SelectLoad - Select and emit code to implement load instructions.
1095///
1096bool X86FastISel::X86SelectLoad(const Instruction *I) {
1097 const LoadInst *LI = cast<LoadInst>(I);
1098
1099 // Atomic loads need special handling.
1100 if (LI->isAtomic())
1101 return false;
1102
1103 MVT VT;
1104 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1105 return false;
1106
1107 const Value *Ptr = LI->getPointerOperand();
1108
1109 X86AddressMode AM;
1110 if (!X86SelectAddress(Ptr, AM))
1111 return false;
1112
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001113 unsigned Alignment = LI->getAlignment();
1114 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1115 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1116 Alignment = ABIAlignment;
1117
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001118 unsigned ResultReg = 0;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001119 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1120 Alignment))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001121 return false;
1122
1123 updateValueMap(I, ResultReg);
1124 return true;
1125}
1126
1127static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1128 bool HasAVX = Subtarget->hasAVX();
1129 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1130 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1131
1132 switch (VT.getSimpleVT().SimpleTy) {
1133 default: return 0;
1134 case MVT::i8: return X86::CMP8rr;
1135 case MVT::i16: return X86::CMP16rr;
1136 case MVT::i32: return X86::CMP32rr;
1137 case MVT::i64: return X86::CMP64rr;
1138 case MVT::f32:
1139 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1140 case MVT::f64:
1141 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1142 }
1143}
1144
Rafael Espindola19141f22015-03-16 14:05:49 +00001145/// If we have a comparison with RHS as the RHS of the comparison, return an
1146/// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001147static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
Rafael Espindola933f51a2015-03-16 14:25:08 +00001148 int64_t Val = RHSC->getSExtValue();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001149 switch (VT.getSimpleVT().SimpleTy) {
1150 // Otherwise, we can't fold the immediate into this comparison.
Rafael Espindola19141f22015-03-16 14:05:49 +00001151 default:
1152 return 0;
1153 case MVT::i8:
1154 return X86::CMP8ri;
1155 case MVT::i16:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001156 if (isInt<8>(Val))
1157 return X86::CMP16ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001158 return X86::CMP16ri;
1159 case MVT::i32:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001160 if (isInt<8>(Val))
1161 return X86::CMP32ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001162 return X86::CMP32ri;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001163 case MVT::i64:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001164 if (isInt<8>(Val))
1165 return X86::CMP64ri8;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001166 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1167 // field.
Rafael Espindola933f51a2015-03-16 14:25:08 +00001168 if (isInt<32>(Val))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001169 return X86::CMP64ri32;
1170 return 0;
1171 }
1172}
1173
1174bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1175 EVT VT, DebugLoc CurDbgLoc) {
1176 unsigned Op0Reg = getRegForValue(Op0);
1177 if (Op0Reg == 0) return false;
1178
1179 // Handle 'null' like i32/i64 0.
1180 if (isa<ConstantPointerNull>(Op1))
1181 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1182
1183 // We have two options: compare with register or immediate. If the RHS of
1184 // the compare is an immediate that we can fold into this compare, use
1185 // CMPri, otherwise use CMPrr.
1186 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1187 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1188 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1189 .addReg(Op0Reg)
1190 .addImm(Op1C->getSExtValue());
1191 return true;
1192 }
1193 }
1194
1195 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1196 if (CompareOpc == 0) return false;
1197
1198 unsigned Op1Reg = getRegForValue(Op1);
1199 if (Op1Reg == 0) return false;
1200 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1201 .addReg(Op0Reg)
1202 .addReg(Op1Reg);
1203
1204 return true;
1205}
1206
1207bool X86FastISel::X86SelectCmp(const Instruction *I) {
1208 const CmpInst *CI = cast<CmpInst>(I);
1209
1210 MVT VT;
1211 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1212 return false;
1213
1214 // Try to optimize or fold the cmp.
1215 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1216 unsigned ResultReg = 0;
1217 switch (Predicate) {
1218 default: break;
1219 case CmpInst::FCMP_FALSE: {
1220 ResultReg = createResultReg(&X86::GR32RegClass);
1221 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1222 ResultReg);
1223 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1224 X86::sub_8bit);
1225 if (!ResultReg)
1226 return false;
1227 break;
1228 }
1229 case CmpInst::FCMP_TRUE: {
1230 ResultReg = createResultReg(&X86::GR8RegClass);
1231 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1232 ResultReg).addImm(1);
1233 break;
1234 }
1235 }
1236
1237 if (ResultReg) {
1238 updateValueMap(I, ResultReg);
1239 return true;
1240 }
1241
1242 const Value *LHS = CI->getOperand(0);
1243 const Value *RHS = CI->getOperand(1);
1244
1245 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1246 // We don't have to materialize a zero constant for this case and can just use
1247 // %x again on the RHS.
1248 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1249 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1250 if (RHSC && RHSC->isNullValue())
1251 RHS = LHS;
1252 }
1253
1254 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1255 static unsigned SETFOpcTable[2][3] = {
1256 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1257 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1258 };
1259 unsigned *SETFOpc = nullptr;
1260 switch (Predicate) {
1261 default: break;
1262 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1263 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1264 }
1265
1266 ResultReg = createResultReg(&X86::GR8RegClass);
1267 if (SETFOpc) {
1268 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1269 return false;
1270
1271 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1272 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1273 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1274 FlagReg1);
1275 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1276 FlagReg2);
1277 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1278 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1279 updateValueMap(I, ResultReg);
1280 return true;
1281 }
1282
1283 X86::CondCode CC;
1284 bool SwapArgs;
1285 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1286 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1287 unsigned Opc = X86::getSETFromCond(CC);
1288
1289 if (SwapArgs)
1290 std::swap(LHS, RHS);
1291
1292 // Emit a compare of LHS/RHS.
1293 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1294 return false;
1295
1296 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1297 updateValueMap(I, ResultReg);
1298 return true;
1299}
1300
1301bool X86FastISel::X86SelectZExt(const Instruction *I) {
1302 EVT DstVT = TLI.getValueType(I->getType());
1303 if (!TLI.isTypeLegal(DstVT))
1304 return false;
1305
1306 unsigned ResultReg = getRegForValue(I->getOperand(0));
1307 if (ResultReg == 0)
1308 return false;
1309
1310 // Handle zero-extension from i1 to i8, which is common.
1311 MVT SrcVT = TLI.getSimpleValueType(I->getOperand(0)->getType());
1312 if (SrcVT.SimpleTy == MVT::i1) {
1313 // Set the high bits to zero.
1314 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1315 SrcVT = MVT::i8;
1316
1317 if (ResultReg == 0)
1318 return false;
1319 }
1320
1321 if (DstVT == MVT::i64) {
1322 // Handle extension to 64-bits via sub-register shenanigans.
1323 unsigned MovInst;
1324
1325 switch (SrcVT.SimpleTy) {
1326 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1327 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1328 case MVT::i32: MovInst = X86::MOV32rr; break;
1329 default: llvm_unreachable("Unexpected zext to i64 source type");
1330 }
1331
1332 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1333 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1334 .addReg(ResultReg);
1335
1336 ResultReg = createResultReg(&X86::GR64RegClass);
1337 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1338 ResultReg)
1339 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1340 } else if (DstVT != MVT::i8) {
1341 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1342 ResultReg, /*Kill=*/true);
1343 if (ResultReg == 0)
1344 return false;
1345 }
1346
1347 updateValueMap(I, ResultReg);
1348 return true;
1349}
1350
1351bool X86FastISel::X86SelectBranch(const Instruction *I) {
1352 // Unconditional branches are selected by tablegen-generated code.
1353 // Handle a conditional branch.
1354 const BranchInst *BI = cast<BranchInst>(I);
1355 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1356 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1357
1358 // Fold the common case of a conditional branch with a comparison
1359 // in the same block (values defined on other blocks may not have
1360 // initialized registers).
1361 X86::CondCode CC;
1362 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1363 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1364 EVT VT = TLI.getValueType(CI->getOperand(0)->getType());
1365
1366 // Try to optimize or fold the cmp.
1367 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1368 switch (Predicate) {
1369 default: break;
1370 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1371 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1372 }
1373
1374 const Value *CmpLHS = CI->getOperand(0);
1375 const Value *CmpRHS = CI->getOperand(1);
1376
1377 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1378 // 0.0.
1379 // We don't have to materialize a zero constant for this case and can just
1380 // use %x again on the RHS.
1381 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1382 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1383 if (CmpRHSC && CmpRHSC->isNullValue())
1384 CmpRHS = CmpLHS;
1385 }
1386
1387 // Try to take advantage of fallthrough opportunities.
1388 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1389 std::swap(TrueMBB, FalseMBB);
1390 Predicate = CmpInst::getInversePredicate(Predicate);
1391 }
1392
1393 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1394 // code check. Instead two branch instructions are required to check all
1395 // the flags. First we change the predicate to a supported condition code,
1396 // which will be the first branch. Later one we will emit the second
1397 // branch.
1398 bool NeedExtraBranch = false;
1399 switch (Predicate) {
1400 default: break;
1401 case CmpInst::FCMP_OEQ:
1402 std::swap(TrueMBB, FalseMBB); // fall-through
1403 case CmpInst::FCMP_UNE:
1404 NeedExtraBranch = true;
1405 Predicate = CmpInst::FCMP_ONE;
1406 break;
1407 }
1408
1409 bool SwapArgs;
1410 unsigned BranchOpc;
1411 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1412 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1413
1414 BranchOpc = X86::GetCondBranchFromCond(CC);
1415 if (SwapArgs)
1416 std::swap(CmpLHS, CmpRHS);
1417
1418 // Emit a compare of the LHS and RHS, setting the flags.
1419 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1420 return false;
1421
1422 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1423 .addMBB(TrueMBB);
1424
1425 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1426 // to UNE above).
1427 if (NeedExtraBranch) {
1428 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1429 .addMBB(TrueMBB);
1430 }
1431
1432 // Obtain the branch weight and add the TrueBB to the successor list.
1433 uint32_t BranchWeight = 0;
1434 if (FuncInfo.BPI)
1435 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1436 TrueMBB->getBasicBlock());
1437 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1438
1439 // Emits an unconditional branch to the FalseBB, obtains the branch
1440 // weight, and adds it to the successor list.
1441 fastEmitBranch(FalseMBB, DbgLoc);
1442
1443 return true;
1444 }
1445 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1446 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1447 // typically happen for _Bool and C++ bools.
1448 MVT SourceVT;
1449 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1450 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1451 unsigned TestOpc = 0;
1452 switch (SourceVT.SimpleTy) {
1453 default: break;
1454 case MVT::i8: TestOpc = X86::TEST8ri; break;
1455 case MVT::i16: TestOpc = X86::TEST16ri; break;
1456 case MVT::i32: TestOpc = X86::TEST32ri; break;
1457 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1458 }
1459 if (TestOpc) {
1460 unsigned OpReg = getRegForValue(TI->getOperand(0));
1461 if (OpReg == 0) return false;
1462 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1463 .addReg(OpReg).addImm(1);
1464
1465 unsigned JmpOpc = X86::JNE_1;
1466 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1467 std::swap(TrueMBB, FalseMBB);
1468 JmpOpc = X86::JE_1;
1469 }
1470
1471 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1472 .addMBB(TrueMBB);
1473 fastEmitBranch(FalseMBB, DbgLoc);
1474 uint32_t BranchWeight = 0;
1475 if (FuncInfo.BPI)
1476 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1477 TrueMBB->getBasicBlock());
1478 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1479 return true;
1480 }
1481 }
1482 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1483 // Fake request the condition, otherwise the intrinsic might be completely
1484 // optimized away.
1485 unsigned TmpReg = getRegForValue(BI->getCondition());
1486 if (TmpReg == 0)
1487 return false;
1488
1489 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1490
1491 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1492 .addMBB(TrueMBB);
1493 fastEmitBranch(FalseMBB, DbgLoc);
1494 uint32_t BranchWeight = 0;
1495 if (FuncInfo.BPI)
1496 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1497 TrueMBB->getBasicBlock());
1498 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1499 return true;
1500 }
1501
1502 // Otherwise do a clumsy setcc and re-test it.
1503 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1504 // in an explicit cast, so make sure to handle that correctly.
1505 unsigned OpReg = getRegForValue(BI->getCondition());
1506 if (OpReg == 0) return false;
1507
1508 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1509 .addReg(OpReg).addImm(1);
1510 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1511 .addMBB(TrueMBB);
1512 fastEmitBranch(FalseMBB, DbgLoc);
1513 uint32_t BranchWeight = 0;
1514 if (FuncInfo.BPI)
1515 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
1516 TrueMBB->getBasicBlock());
1517 FuncInfo.MBB->addSuccessor(TrueMBB, BranchWeight);
1518 return true;
1519}
1520
1521bool X86FastISel::X86SelectShift(const Instruction *I) {
1522 unsigned CReg = 0, OpReg = 0;
1523 const TargetRegisterClass *RC = nullptr;
1524 if (I->getType()->isIntegerTy(8)) {
1525 CReg = X86::CL;
1526 RC = &X86::GR8RegClass;
1527 switch (I->getOpcode()) {
1528 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1529 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1530 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1531 default: return false;
1532 }
1533 } else if (I->getType()->isIntegerTy(16)) {
1534 CReg = X86::CX;
1535 RC = &X86::GR16RegClass;
1536 switch (I->getOpcode()) {
1537 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1538 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1539 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1540 default: return false;
1541 }
1542 } else if (I->getType()->isIntegerTy(32)) {
1543 CReg = X86::ECX;
1544 RC = &X86::GR32RegClass;
1545 switch (I->getOpcode()) {
1546 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1547 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1548 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1549 default: return false;
1550 }
1551 } else if (I->getType()->isIntegerTy(64)) {
1552 CReg = X86::RCX;
1553 RC = &X86::GR64RegClass;
1554 switch (I->getOpcode()) {
1555 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1556 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1557 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1558 default: return false;
1559 }
1560 } else {
1561 return false;
1562 }
1563
1564 MVT VT;
1565 if (!isTypeLegal(I->getType(), VT))
1566 return false;
1567
1568 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1569 if (Op0Reg == 0) return false;
1570
1571 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1572 if (Op1Reg == 0) return false;
1573 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1574 CReg).addReg(Op1Reg);
1575
1576 // The shift instruction uses X86::CL. If we defined a super-register
1577 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1578 if (CReg != X86::CL)
1579 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1580 TII.get(TargetOpcode::KILL), X86::CL)
1581 .addReg(CReg, RegState::Kill);
1582
1583 unsigned ResultReg = createResultReg(RC);
1584 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1585 .addReg(Op0Reg);
1586 updateValueMap(I, ResultReg);
1587 return true;
1588}
1589
1590bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1591 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1592 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1593 const static bool S = true; // IsSigned
1594 const static bool U = false; // !IsSigned
1595 const static unsigned Copy = TargetOpcode::COPY;
1596 // For the X86 DIV/IDIV instruction, in most cases the dividend
1597 // (numerator) must be in a specific register pair highreg:lowreg,
1598 // producing the quotient in lowreg and the remainder in highreg.
1599 // For most data types, to set up the instruction, the dividend is
1600 // copied into lowreg, and lowreg is sign-extended or zero-extended
1601 // into highreg. The exception is i8, where the dividend is defined
1602 // as a single register rather than a register pair, and we
1603 // therefore directly sign-extend or zero-extend the dividend into
1604 // lowreg, instead of copying, and ignore the highreg.
1605 const static struct DivRemEntry {
1606 // The following portion depends only on the data type.
1607 const TargetRegisterClass *RC;
1608 unsigned LowInReg; // low part of the register pair
1609 unsigned HighInReg; // high part of the register pair
1610 // The following portion depends on both the data type and the operation.
1611 struct DivRemResult {
1612 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1613 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1614 // highreg, or copying a zero into highreg.
1615 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1616 // zero/sign-extending into lowreg for i8.
1617 unsigned DivRemResultReg; // Register containing the desired result.
1618 bool IsOpSigned; // Whether to use signed or unsigned form.
1619 } ResultTable[NumOps];
1620 } OpTable[NumTypes] = {
1621 { &X86::GR8RegClass, X86::AX, 0, {
1622 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1623 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1624 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1625 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1626 }
1627 }, // i8
1628 { &X86::GR16RegClass, X86::AX, X86::DX, {
1629 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1630 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1631 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1632 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1633 }
1634 }, // i16
1635 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1636 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1637 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1638 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1639 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1640 }
1641 }, // i32
1642 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1643 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1644 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1645 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1646 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1647 }
1648 }, // i64
1649 };
1650
1651 MVT VT;
1652 if (!isTypeLegal(I->getType(), VT))
1653 return false;
1654
1655 unsigned TypeIndex, OpIndex;
1656 switch (VT.SimpleTy) {
1657 default: return false;
1658 case MVT::i8: TypeIndex = 0; break;
1659 case MVT::i16: TypeIndex = 1; break;
1660 case MVT::i32: TypeIndex = 2; break;
1661 case MVT::i64: TypeIndex = 3;
1662 if (!Subtarget->is64Bit())
1663 return false;
1664 break;
1665 }
1666
1667 switch (I->getOpcode()) {
1668 default: llvm_unreachable("Unexpected div/rem opcode");
1669 case Instruction::SDiv: OpIndex = 0; break;
1670 case Instruction::SRem: OpIndex = 1; break;
1671 case Instruction::UDiv: OpIndex = 2; break;
1672 case Instruction::URem: OpIndex = 3; break;
1673 }
1674
1675 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1676 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1677 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1678 if (Op0Reg == 0)
1679 return false;
1680 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1681 if (Op1Reg == 0)
1682 return false;
1683
1684 // Move op0 into low-order input register.
1685 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1686 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1687 // Zero-extend or sign-extend into high-order input register.
1688 if (OpEntry.OpSignExtend) {
1689 if (OpEntry.IsOpSigned)
1690 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1691 TII.get(OpEntry.OpSignExtend));
1692 else {
1693 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1694 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1695 TII.get(X86::MOV32r0), Zero32);
1696
1697 // Copy the zero into the appropriate sub/super/identical physical
1698 // register. Unfortunately the operations needed are not uniform enough
1699 // to fit neatly into the table above.
1700 if (VT.SimpleTy == MVT::i16) {
1701 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1702 TII.get(Copy), TypeEntry.HighInReg)
1703 .addReg(Zero32, 0, X86::sub_16bit);
1704 } else if (VT.SimpleTy == MVT::i32) {
1705 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1706 TII.get(Copy), TypeEntry.HighInReg)
1707 .addReg(Zero32);
1708 } else if (VT.SimpleTy == MVT::i64) {
1709 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1710 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1711 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1712 }
1713 }
1714 }
1715 // Generate the DIV/IDIV instruction.
1716 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1717 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1718 // For i8 remainder, we can't reference AH directly, as we'll end
1719 // up with bogus copies like %R9B = COPY %AH. Reference AX
1720 // instead to prevent AH references in a REX instruction.
1721 //
1722 // The current assumption of the fast register allocator is that isel
1723 // won't generate explicit references to the GPR8_NOREX registers. If
1724 // the allocator and/or the backend get enhanced to be more robust in
1725 // that regard, this can be, and should be, removed.
1726 unsigned ResultReg = 0;
1727 if ((I->getOpcode() == Instruction::SRem ||
1728 I->getOpcode() == Instruction::URem) &&
1729 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1730 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1731 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1732 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1733 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1734
1735 // Shift AX right by 8 bits instead of using AH.
1736 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1737 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1738
1739 // Now reference the 8-bit subreg of the result.
1740 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1741 /*Kill=*/true, X86::sub_8bit);
1742 }
1743 // Copy the result out of the physreg if we haven't already.
1744 if (!ResultReg) {
1745 ResultReg = createResultReg(TypeEntry.RC);
1746 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1747 .addReg(OpEntry.DivRemResultReg);
1748 }
1749 updateValueMap(I, ResultReg);
1750
1751 return true;
1752}
1753
1754/// \brief Emit a conditional move instruction (if the are supported) to lower
1755/// the select.
1756bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1757 // Check if the subtarget supports these instructions.
1758 if (!Subtarget->hasCMov())
1759 return false;
1760
1761 // FIXME: Add support for i8.
1762 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1763 return false;
1764
1765 const Value *Cond = I->getOperand(0);
1766 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1767 bool NeedTest = true;
1768 X86::CondCode CC = X86::COND_NE;
1769
1770 // Optimize conditions coming from a compare if both instructions are in the
1771 // same basic block (values defined in other basic blocks may not have
1772 // initialized registers).
1773 const auto *CI = dyn_cast<CmpInst>(Cond);
1774 if (CI && (CI->getParent() == I->getParent())) {
1775 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1776
1777 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1778 static unsigned SETFOpcTable[2][3] = {
1779 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1780 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1781 };
1782 unsigned *SETFOpc = nullptr;
1783 switch (Predicate) {
1784 default: break;
1785 case CmpInst::FCMP_OEQ:
1786 SETFOpc = &SETFOpcTable[0][0];
1787 Predicate = CmpInst::ICMP_NE;
1788 break;
1789 case CmpInst::FCMP_UNE:
1790 SETFOpc = &SETFOpcTable[1][0];
1791 Predicate = CmpInst::ICMP_NE;
1792 break;
1793 }
1794
1795 bool NeedSwap;
1796 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1797 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1798
1799 const Value *CmpLHS = CI->getOperand(0);
1800 const Value *CmpRHS = CI->getOperand(1);
1801 if (NeedSwap)
1802 std::swap(CmpLHS, CmpRHS);
1803
1804 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
1805 // Emit a compare of the LHS and RHS, setting the flags.
1806 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1807 return false;
1808
1809 if (SETFOpc) {
1810 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1811 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1812 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1813 FlagReg1);
1814 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1815 FlagReg2);
1816 auto const &II = TII.get(SETFOpc[2]);
1817 if (II.getNumDefs()) {
1818 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1819 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1820 .addReg(FlagReg2).addReg(FlagReg1);
1821 } else {
1822 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1823 .addReg(FlagReg2).addReg(FlagReg1);
1824 }
1825 }
1826 NeedTest = false;
1827 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1828 // Fake request the condition, otherwise the intrinsic might be completely
1829 // optimized away.
1830 unsigned TmpReg = getRegForValue(Cond);
1831 if (TmpReg == 0)
1832 return false;
1833
1834 NeedTest = false;
1835 }
1836
1837 if (NeedTest) {
1838 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1839 // garbage. Indeed, only the less significant bit is supposed to be
1840 // accurate. If we read more than the lsb, we may see non-zero values
1841 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1842 // the select. This is achieved by performing TEST against 1.
1843 unsigned CondReg = getRegForValue(Cond);
1844 if (CondReg == 0)
1845 return false;
1846 bool CondIsKill = hasTrivialKill(Cond);
1847
1848 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1849 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1850 }
1851
1852 const Value *LHS = I->getOperand(1);
1853 const Value *RHS = I->getOperand(2);
1854
1855 unsigned RHSReg = getRegForValue(RHS);
1856 bool RHSIsKill = hasTrivialKill(RHS);
1857
1858 unsigned LHSReg = getRegForValue(LHS);
1859 bool LHSIsKill = hasTrivialKill(LHS);
1860
1861 if (!LHSReg || !RHSReg)
1862 return false;
1863
1864 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
1865 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1866 LHSReg, LHSIsKill);
1867 updateValueMap(I, ResultReg);
1868 return true;
1869}
1870
Sanjay Patel302404b2015-03-05 21:46:54 +00001871/// \brief Emit SSE or AVX instructions to lower the select.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001872///
1873/// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1874/// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
Sanjay Patel302404b2015-03-05 21:46:54 +00001875/// SSE instructions are available. If AVX is available, try to use a VBLENDV.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001876bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
1877 // Optimize conditions coming from a compare if both instructions are in the
1878 // same basic block (values defined in other basic blocks may not have
1879 // initialized registers).
1880 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1881 if (!CI || (CI->getParent() != I->getParent()))
1882 return false;
1883
1884 if (I->getType() != CI->getOperand(0)->getType() ||
1885 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1886 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
1887 return false;
1888
1889 const Value *CmpLHS = CI->getOperand(0);
1890 const Value *CmpRHS = CI->getOperand(1);
1891 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1892
1893 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1894 // We don't have to materialize a zero constant for this case and can just use
1895 // %x again on the RHS.
1896 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1897 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1898 if (CmpRHSC && CmpRHSC->isNullValue())
1899 CmpRHS = CmpLHS;
1900 }
1901
1902 unsigned CC;
1903 bool NeedSwap;
1904 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
1905 if (CC > 7)
1906 return false;
1907
1908 if (NeedSwap)
1909 std::swap(CmpLHS, CmpRHS);
1910
Sanjay Patel302404b2015-03-05 21:46:54 +00001911 // Choose the SSE instruction sequence based on data type (float or double).
1912 static unsigned OpcTable[2][4] = {
1913 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1914 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001915 };
1916
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001917 unsigned *Opc = nullptr;
1918 switch (RetVT.SimpleTy) {
1919 default: return false;
Sanjay Patel302404b2015-03-05 21:46:54 +00001920 case MVT::f32: Opc = &OpcTable[0][0]; break;
1921 case MVT::f64: Opc = &OpcTable[1][0]; break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001922 }
1923
1924 const Value *LHS = I->getOperand(1);
1925 const Value *RHS = I->getOperand(2);
1926
1927 unsigned LHSReg = getRegForValue(LHS);
1928 bool LHSIsKill = hasTrivialKill(LHS);
1929
1930 unsigned RHSReg = getRegForValue(RHS);
1931 bool RHSIsKill = hasTrivialKill(RHS);
1932
1933 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1934 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1935
1936 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1937 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1938
1939 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1940 return false;
1941
1942 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
Sanjay Patel302404b2015-03-05 21:46:54 +00001943 unsigned ResultReg;
1944
1945 if (Subtarget->hasAVX()) {
1946 // If we have AVX, create 1 blendv instead of 3 logic instructions.
1947 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
1948 // uses XMM0 as the selection register. That may need just as many
1949 // instructions as the AND/ANDN/OR sequence due to register moves, so
1950 // don't bother.
1951 unsigned CmpOpcode =
1952 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
1953 unsigned BlendOpcode =
1954 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
1955
1956 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, RC, CmpLHSReg, CmpLHSIsKill,
1957 CmpRHSReg, CmpRHSIsKill, CC);
1958 ResultReg = fastEmitInst_rrr(BlendOpcode, RC, RHSReg, RHSIsKill,
1959 LHSReg, LHSIsKill, CmpReg, true);
1960 } else {
1961 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
1962 CmpRHSReg, CmpRHSIsKill, CC);
1963 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
1964 LHSReg, LHSIsKill);
1965 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
1966 RHSReg, RHSIsKill);
1967 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
1968 AndReg, /*IsKill=*/true);
1969 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001970 updateValueMap(I, ResultReg);
1971 return true;
1972}
1973
1974bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
1975 // These are pseudo CMOV instructions and will be later expanded into control-
1976 // flow.
1977 unsigned Opc;
1978 switch (RetVT.SimpleTy) {
1979 default: return false;
1980 case MVT::i8: Opc = X86::CMOV_GR8; break;
1981 case MVT::i16: Opc = X86::CMOV_GR16; break;
1982 case MVT::i32: Opc = X86::CMOV_GR32; break;
1983 case MVT::f32: Opc = X86::CMOV_FR32; break;
1984 case MVT::f64: Opc = X86::CMOV_FR64; break;
1985 }
1986
1987 const Value *Cond = I->getOperand(0);
1988 X86::CondCode CC = X86::COND_NE;
1989
1990 // Optimize conditions coming from a compare if both instructions are in the
1991 // same basic block (values defined in other basic blocks may not have
1992 // initialized registers).
1993 const auto *CI = dyn_cast<CmpInst>(Cond);
1994 if (CI && (CI->getParent() == I->getParent())) {
1995 bool NeedSwap;
1996 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
1997 if (CC > X86::LAST_VALID_COND)
1998 return false;
1999
2000 const Value *CmpLHS = CI->getOperand(0);
2001 const Value *CmpRHS = CI->getOperand(1);
2002
2003 if (NeedSwap)
2004 std::swap(CmpLHS, CmpRHS);
2005
2006 EVT CmpVT = TLI.getValueType(CmpLHS->getType());
2007 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2008 return false;
2009 } else {
2010 unsigned CondReg = getRegForValue(Cond);
2011 if (CondReg == 0)
2012 return false;
2013 bool CondIsKill = hasTrivialKill(Cond);
2014 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2015 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2016 }
2017
2018 const Value *LHS = I->getOperand(1);
2019 const Value *RHS = I->getOperand(2);
2020
2021 unsigned LHSReg = getRegForValue(LHS);
2022 bool LHSIsKill = hasTrivialKill(LHS);
2023
2024 unsigned RHSReg = getRegForValue(RHS);
2025 bool RHSIsKill = hasTrivialKill(RHS);
2026
2027 if (!LHSReg || !RHSReg)
2028 return false;
2029
2030 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2031
2032 unsigned ResultReg =
2033 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2034 updateValueMap(I, ResultReg);
2035 return true;
2036}
2037
2038bool X86FastISel::X86SelectSelect(const Instruction *I) {
2039 MVT RetVT;
2040 if (!isTypeLegal(I->getType(), RetVT))
2041 return false;
2042
2043 // Check if we can fold the select.
2044 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2045 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2046 const Value *Opnd = nullptr;
2047 switch (Predicate) {
2048 default: break;
2049 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2050 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2051 }
2052 // No need for a select anymore - this is an unconditional move.
2053 if (Opnd) {
2054 unsigned OpReg = getRegForValue(Opnd);
2055 if (OpReg == 0)
2056 return false;
2057 bool OpIsKill = hasTrivialKill(Opnd);
2058 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2059 unsigned ResultReg = createResultReg(RC);
2060 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2061 TII.get(TargetOpcode::COPY), ResultReg)
2062 .addReg(OpReg, getKillRegState(OpIsKill));
2063 updateValueMap(I, ResultReg);
2064 return true;
2065 }
2066 }
2067
2068 // First try to use real conditional move instructions.
2069 if (X86FastEmitCMoveSelect(RetVT, I))
2070 return true;
2071
2072 // Try to use a sequence of SSE instructions to simulate a conditional move.
2073 if (X86FastEmitSSESelect(RetVT, I))
2074 return true;
2075
2076 // Fall-back to pseudo conditional move instructions, which will be later
2077 // converted to control-flow.
2078 if (X86FastEmitPseudoSelect(RetVT, I))
2079 return true;
2080
2081 return false;
2082}
2083
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002084bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
Andrea Di Biagio98c36702015-04-20 11:56:59 +00002085 // The target-independent selection algorithm in FastISel already knows how
2086 // to select a SINT_TO_FP if the target is SSE but not AVX.
2087 // Early exit if the subtarget doesn't have AVX.
2088 if (!Subtarget->hasAVX())
2089 return false;
2090
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002091 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2092 return false;
2093
2094 // Select integer to float/double conversion.
2095 unsigned OpReg = getRegForValue(I->getOperand(0));
2096 if (OpReg == 0)
2097 return false;
2098
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002099 const TargetRegisterClass *RC = nullptr;
2100 unsigned Opcode;
2101
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002102 if (I->getType()->isDoubleTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002103 // sitofp int -> double
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002104 Opcode = X86::VCVTSI2SDrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002105 RC = &X86::FR64RegClass;
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002106 } else if (I->getType()->isFloatTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002107 // sitofp int -> float
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002108 Opcode = X86::VCVTSI2SSrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002109 RC = &X86::FR32RegClass;
2110 } else
2111 return false;
2112
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002113 unsigned ImplicitDefReg = createResultReg(RC);
2114 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2115 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2116 unsigned ResultReg =
2117 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002118 updateValueMap(I, ResultReg);
2119 return true;
2120}
2121
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002122// Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2123bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2124 unsigned TargetOpc,
2125 const TargetRegisterClass *RC) {
2126 assert((I->getOpcode() == Instruction::FPExt ||
2127 I->getOpcode() == Instruction::FPTrunc) &&
2128 "Instruction must be an FPExt or FPTrunc!");
2129
2130 unsigned OpReg = getRegForValue(I->getOperand(0));
2131 if (OpReg == 0)
2132 return false;
2133
2134 unsigned ResultReg = createResultReg(RC);
2135 MachineInstrBuilder MIB;
2136 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2137 ResultReg);
2138 if (Subtarget->hasAVX())
2139 MIB.addReg(OpReg);
2140 MIB.addReg(OpReg);
2141 updateValueMap(I, ResultReg);
2142 return true;
2143}
2144
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002145bool X86FastISel::X86SelectFPExt(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002146 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2147 I->getOperand(0)->getType()->isFloatTy()) {
2148 // fpext from float to double.
2149 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2150 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002151 }
2152
2153 return false;
2154}
2155
2156bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002157 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2158 I->getOperand(0)->getType()->isDoubleTy()) {
2159 // fptrunc from double to float.
2160 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2161 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002162 }
2163
2164 return false;
2165}
2166
2167bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2168 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
2169 EVT DstVT = TLI.getValueType(I->getType());
2170
2171 // This code only handles truncation to byte.
2172 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2173 return false;
2174 if (!TLI.isTypeLegal(SrcVT))
2175 return false;
2176
2177 unsigned InputReg = getRegForValue(I->getOperand(0));
2178 if (!InputReg)
2179 // Unhandled operand. Halt "fast" selection and bail.
2180 return false;
2181
2182 if (SrcVT == MVT::i8) {
2183 // Truncate from i8 to i1; no code needed.
2184 updateValueMap(I, InputReg);
2185 return true;
2186 }
2187
2188 if (!Subtarget->is64Bit()) {
2189 // If we're on x86-32; we can't extract an i8 from a general register.
2190 // First issue a copy to GR16_ABCD or GR32_ABCD.
2191 const TargetRegisterClass *CopyRC =
2192 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2193 unsigned CopyReg = createResultReg(CopyRC);
2194 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2195 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2196 InputReg = CopyReg;
2197 }
2198
2199 // Issue an extract_subreg.
2200 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
2201 InputReg, /*Kill=*/true,
2202 X86::sub_8bit);
2203 if (!ResultReg)
2204 return false;
2205
2206 updateValueMap(I, ResultReg);
2207 return true;
2208}
2209
2210bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2211 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2212}
2213
2214bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2215 X86AddressMode SrcAM, uint64_t Len) {
2216
2217 // Make sure we don't bloat code by inlining very large memcpy's.
2218 if (!IsMemcpySmall(Len))
2219 return false;
2220
2221 bool i64Legal = Subtarget->is64Bit();
2222
2223 // We don't care about alignment here since we just emit integer accesses.
2224 while (Len) {
2225 MVT VT;
2226 if (Len >= 8 && i64Legal)
2227 VT = MVT::i64;
2228 else if (Len >= 4)
2229 VT = MVT::i32;
2230 else if (Len >= 2)
2231 VT = MVT::i16;
2232 else
2233 VT = MVT::i8;
2234
2235 unsigned Reg;
2236 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2237 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2238 assert(RV && "Failed to emit load or store??");
2239
2240 unsigned Size = VT.getSizeInBits()/8;
2241 Len -= Size;
2242 DestAM.Disp += Size;
2243 SrcAM.Disp += Size;
2244 }
2245
2246 return true;
2247}
2248
2249bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2250 // FIXME: Handle more intrinsics.
2251 switch (II->getIntrinsicID()) {
2252 default: return false;
Andrea Di Biagio70351782015-02-20 19:37:14 +00002253 case Intrinsic::convert_from_fp16:
2254 case Intrinsic::convert_to_fp16: {
2255 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C())
2256 return false;
2257
2258 const Value *Op = II->getArgOperand(0);
2259 unsigned InputReg = getRegForValue(Op);
2260 if (InputReg == 0)
2261 return false;
2262
2263 // F16C only allows converting from float to half and from half to float.
2264 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2265 if (IsFloatToHalf) {
2266 if (!Op->getType()->isFloatTy())
2267 return false;
2268 } else {
2269 if (!II->getType()->isFloatTy())
2270 return false;
2271 }
2272
2273 unsigned ResultReg = 0;
2274 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2275 if (IsFloatToHalf) {
2276 // 'InputReg' is implicitly promoted from register class FR32 to
2277 // register class VR128 by method 'constrainOperandRegClass' which is
2278 // directly called by 'fastEmitInst_ri'.
2279 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
2280 // used to provide rounding control.
2281 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 0);
2282
2283 // Move the lower 32-bits of ResultReg to another register of class GR32.
2284 ResultReg = createResultReg(&X86::GR32RegClass);
2285 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2286 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2287 .addReg(InputReg, RegState::Kill);
2288
2289 // The result value is in the lower 16-bits of ResultReg.
2290 unsigned RegIdx = X86::sub_16bit;
2291 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2292 } else {
2293 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2294 // Explicitly sign-extend the input to 32-bit.
2295 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2296 /*Kill=*/false);
2297
2298 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2299 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2300 InputReg, /*Kill=*/true);
2301
2302 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2303
2304 // The result value is in the lower 32-bits of ResultReg.
2305 // Emit an explicit copy from register class VR128 to register class FR32.
2306 ResultReg = createResultReg(&X86::FR32RegClass);
2307 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2308 TII.get(TargetOpcode::COPY), ResultReg)
2309 .addReg(InputReg, RegState::Kill);
2310 }
2311
2312 updateValueMap(II, ResultReg);
2313 return true;
2314 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002315 case Intrinsic::frameaddress: {
David Majnemerca194852015-02-10 22:00:34 +00002316 MachineFunction *MF = FuncInfo.MF;
2317 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2318 return false;
2319
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002320 Type *RetTy = II->getCalledFunction()->getReturnType();
2321
2322 MVT VT;
2323 if (!isTypeLegal(RetTy, VT))
2324 return false;
2325
2326 unsigned Opc;
2327 const TargetRegisterClass *RC = nullptr;
2328
2329 switch (VT.SimpleTy) {
2330 default: llvm_unreachable("Invalid result type for frameaddress.");
2331 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2332 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2333 }
2334
2335 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2336 // we get the wrong frame register.
David Majnemerca194852015-02-10 22:00:34 +00002337 MachineFrameInfo *MFI = MF->getFrameInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002338 MFI->setFrameAddressIsTaken(true);
2339
Eric Christophera1c535b2015-02-02 23:03:45 +00002340 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
David Majnemerca194852015-02-10 22:00:34 +00002341 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002342 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2343 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2344 "Invalid Frame Register!");
2345
2346 // Always make a copy of the frame register to to a vreg first, so that we
2347 // never directly reference the frame register (the TwoAddressInstruction-
2348 // Pass doesn't like that).
2349 unsigned SrcReg = createResultReg(RC);
2350 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2351 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2352
2353 // Now recursively load from the frame address.
2354 // movq (%rbp), %rax
2355 // movq (%rax), %rax
2356 // movq (%rax), %rax
2357 // ...
2358 unsigned DestReg;
2359 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2360 while (Depth--) {
2361 DestReg = createResultReg(RC);
2362 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2363 TII.get(Opc), DestReg), SrcReg);
2364 SrcReg = DestReg;
2365 }
2366
2367 updateValueMap(II, SrcReg);
2368 return true;
2369 }
2370 case Intrinsic::memcpy: {
2371 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2372 // Don't handle volatile or variable length memcpys.
2373 if (MCI->isVolatile())
2374 return false;
2375
2376 if (isa<ConstantInt>(MCI->getLength())) {
2377 // Small memcpy's are common enough that we want to do them
2378 // without a call if possible.
2379 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2380 if (IsMemcpySmall(Len)) {
2381 X86AddressMode DestAM, SrcAM;
2382 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2383 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2384 return false;
2385 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2386 return true;
2387 }
2388 }
2389
2390 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2391 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2392 return false;
2393
2394 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2395 return false;
2396
2397 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
2398 }
2399 case Intrinsic::memset: {
2400 const MemSetInst *MSI = cast<MemSetInst>(II);
2401
2402 if (MSI->isVolatile())
2403 return false;
2404
2405 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2406 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2407 return false;
2408
2409 if (MSI->getDestAddressSpace() > 255)
2410 return false;
2411
2412 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2413 }
2414 case Intrinsic::stackprotector: {
2415 // Emit code to store the stack guard onto the stack.
2416 EVT PtrTy = TLI.getPointerTy();
2417
2418 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2419 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2420
2421 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2422
2423 // Grab the frame index.
2424 X86AddressMode AM;
2425 if (!X86SelectAddress(Slot, AM)) return false;
2426 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2427 return true;
2428 }
2429 case Intrinsic::dbg_declare: {
2430 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2431 X86AddressMode AM;
2432 assert(DI->getAddress() && "Null address should be checked earlier!");
2433 if (!X86SelectAddress(DI->getAddress(), AM))
2434 return false;
2435 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2436 // FIXME may need to add RegState::Debug to any registers produced,
2437 // although ESP/EBP should be the only ones at the moment.
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +00002438 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2439 "Expected inlined-at fields to agree");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002440 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2441 .addImm(0)
2442 .addMetadata(DI->getVariable())
2443 .addMetadata(DI->getExpression());
2444 return true;
2445 }
2446 case Intrinsic::trap: {
2447 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2448 return true;
2449 }
2450 case Intrinsic::sqrt: {
2451 if (!Subtarget->hasSSE1())
2452 return false;
2453
2454 Type *RetTy = II->getCalledFunction()->getReturnType();
2455
2456 MVT VT;
2457 if (!isTypeLegal(RetTy, VT))
2458 return false;
2459
2460 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2461 // is not generated by FastISel yet.
2462 // FIXME: Update this code once tablegen can handle it.
2463 static const unsigned SqrtOpc[2][2] = {
2464 {X86::SQRTSSr, X86::VSQRTSSr},
2465 {X86::SQRTSDr, X86::VSQRTSDr}
2466 };
2467 bool HasAVX = Subtarget->hasAVX();
2468 unsigned Opc;
2469 const TargetRegisterClass *RC;
2470 switch (VT.SimpleTy) {
2471 default: return false;
2472 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2473 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2474 }
2475
2476 const Value *SrcVal = II->getArgOperand(0);
2477 unsigned SrcReg = getRegForValue(SrcVal);
2478
2479 if (SrcReg == 0)
2480 return false;
2481
2482 unsigned ImplicitDefReg = 0;
2483 if (HasAVX) {
2484 ImplicitDefReg = createResultReg(RC);
2485 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2486 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2487 }
2488
2489 unsigned ResultReg = createResultReg(RC);
2490 MachineInstrBuilder MIB;
2491 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2492 ResultReg);
2493
2494 if (ImplicitDefReg)
2495 MIB.addReg(ImplicitDefReg);
2496
2497 MIB.addReg(SrcReg);
2498
2499 updateValueMap(II, ResultReg);
2500 return true;
2501 }
2502 case Intrinsic::sadd_with_overflow:
2503 case Intrinsic::uadd_with_overflow:
2504 case Intrinsic::ssub_with_overflow:
2505 case Intrinsic::usub_with_overflow:
2506 case Intrinsic::smul_with_overflow:
2507 case Intrinsic::umul_with_overflow: {
2508 // This implements the basic lowering of the xalu with overflow intrinsics
2509 // into add/sub/mul followed by either seto or setb.
2510 const Function *Callee = II->getCalledFunction();
2511 auto *Ty = cast<StructType>(Callee->getReturnType());
2512 Type *RetTy = Ty->getTypeAtIndex(0U);
2513 Type *CondTy = Ty->getTypeAtIndex(1);
2514
2515 MVT VT;
2516 if (!isTypeLegal(RetTy, VT))
2517 return false;
2518
2519 if (VT < MVT::i8 || VT > MVT::i64)
2520 return false;
2521
2522 const Value *LHS = II->getArgOperand(0);
2523 const Value *RHS = II->getArgOperand(1);
2524
2525 // Canonicalize immediate to the RHS.
2526 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2527 isCommutativeIntrinsic(II))
2528 std::swap(LHS, RHS);
2529
2530 bool UseIncDec = false;
2531 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2532 UseIncDec = true;
2533
2534 unsigned BaseOpc, CondOpc;
2535 switch (II->getIntrinsicID()) {
2536 default: llvm_unreachable("Unexpected intrinsic!");
2537 case Intrinsic::sadd_with_overflow:
2538 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2539 CondOpc = X86::SETOr;
2540 break;
2541 case Intrinsic::uadd_with_overflow:
2542 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2543 case Intrinsic::ssub_with_overflow:
2544 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2545 CondOpc = X86::SETOr;
2546 break;
2547 case Intrinsic::usub_with_overflow:
2548 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2549 case Intrinsic::smul_with_overflow:
2550 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2551 case Intrinsic::umul_with_overflow:
2552 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2553 }
2554
2555 unsigned LHSReg = getRegForValue(LHS);
2556 if (LHSReg == 0)
2557 return false;
2558 bool LHSIsKill = hasTrivialKill(LHS);
2559
2560 unsigned ResultReg = 0;
2561 // Check if we have an immediate version.
2562 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2563 static const unsigned Opc[2][4] = {
2564 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2565 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2566 };
2567
2568 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2569 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2570 bool IsDec = BaseOpc == X86ISD::DEC;
2571 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2572 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2573 .addReg(LHSReg, getKillRegState(LHSIsKill));
2574 } else
2575 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2576 CI->getZExtValue());
2577 }
2578
2579 unsigned RHSReg;
2580 bool RHSIsKill;
2581 if (!ResultReg) {
2582 RHSReg = getRegForValue(RHS);
2583 if (RHSReg == 0)
2584 return false;
2585 RHSIsKill = hasTrivialKill(RHS);
2586 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2587 RHSIsKill);
2588 }
2589
2590 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2591 // it manually.
2592 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2593 static const unsigned MULOpc[] =
2594 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2595 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2596 // First copy the first operand into RAX, which is an implicit input to
2597 // the X86::MUL*r instruction.
2598 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2599 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2600 .addReg(LHSReg, getKillRegState(LHSIsKill));
2601 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2602 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2603 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2604 static const unsigned MULOpc[] =
2605 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2606 if (VT == MVT::i8) {
2607 // Copy the first operand into AL, which is an implicit input to the
2608 // X86::IMUL8r instruction.
2609 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2610 TII.get(TargetOpcode::COPY), X86::AL)
2611 .addReg(LHSReg, getKillRegState(LHSIsKill));
2612 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2613 RHSIsKill);
2614 } else
2615 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2616 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2617 RHSReg, RHSIsKill);
2618 }
2619
2620 if (!ResultReg)
2621 return false;
2622
2623 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2624 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2625 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2626 ResultReg2);
2627
2628 updateValueMap(II, ResultReg, 2);
2629 return true;
2630 }
2631 case Intrinsic::x86_sse_cvttss2si:
2632 case Intrinsic::x86_sse_cvttss2si64:
2633 case Intrinsic::x86_sse2_cvttsd2si:
2634 case Intrinsic::x86_sse2_cvttsd2si64: {
2635 bool IsInputDouble;
2636 switch (II->getIntrinsicID()) {
2637 default: llvm_unreachable("Unexpected intrinsic.");
2638 case Intrinsic::x86_sse_cvttss2si:
2639 case Intrinsic::x86_sse_cvttss2si64:
2640 if (!Subtarget->hasSSE1())
2641 return false;
2642 IsInputDouble = false;
2643 break;
2644 case Intrinsic::x86_sse2_cvttsd2si:
2645 case Intrinsic::x86_sse2_cvttsd2si64:
2646 if (!Subtarget->hasSSE2())
2647 return false;
2648 IsInputDouble = true;
2649 break;
2650 }
2651
2652 Type *RetTy = II->getCalledFunction()->getReturnType();
2653 MVT VT;
2654 if (!isTypeLegal(RetTy, VT))
2655 return false;
2656
2657 static const unsigned CvtOpc[2][2][2] = {
2658 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2659 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2660 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2661 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2662 };
2663 bool HasAVX = Subtarget->hasAVX();
2664 unsigned Opc;
2665 switch (VT.SimpleTy) {
2666 default: llvm_unreachable("Unexpected result type.");
2667 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2668 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2669 }
2670
2671 // Check if we can fold insertelement instructions into the convert.
2672 const Value *Op = II->getArgOperand(0);
2673 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2674 const Value *Index = IE->getOperand(2);
2675 if (!isa<ConstantInt>(Index))
2676 break;
2677 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2678
2679 if (Idx == 0) {
2680 Op = IE->getOperand(1);
2681 break;
2682 }
2683 Op = IE->getOperand(0);
2684 }
2685
2686 unsigned Reg = getRegForValue(Op);
2687 if (Reg == 0)
2688 return false;
2689
2690 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2691 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2692 .addReg(Reg);
2693
2694 updateValueMap(II, ResultReg);
2695 return true;
2696 }
2697 }
2698}
2699
2700bool X86FastISel::fastLowerArguments() {
2701 if (!FuncInfo.CanLowerReturn)
2702 return false;
2703
2704 const Function *F = FuncInfo.Fn;
2705 if (F->isVarArg())
2706 return false;
2707
2708 CallingConv::ID CC = F->getCallingConv();
2709 if (CC != CallingConv::C)
2710 return false;
2711
2712 if (Subtarget->isCallingConvWin64(CC))
2713 return false;
2714
2715 if (!Subtarget->is64Bit())
2716 return false;
2717
2718 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2719 unsigned GPRCnt = 0;
2720 unsigned FPRCnt = 0;
2721 unsigned Idx = 0;
2722 for (auto const &Arg : F->args()) {
2723 // The first argument is at index 1.
2724 ++Idx;
2725 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2726 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2727 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2728 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2729 return false;
2730
2731 Type *ArgTy = Arg.getType();
2732 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2733 return false;
2734
2735 EVT ArgVT = TLI.getValueType(ArgTy);
2736 if (!ArgVT.isSimple()) return false;
2737 switch (ArgVT.getSimpleVT().SimpleTy) {
2738 default: return false;
2739 case MVT::i32:
2740 case MVT::i64:
2741 ++GPRCnt;
2742 break;
2743 case MVT::f32:
2744 case MVT::f64:
2745 if (!Subtarget->hasSSE1())
2746 return false;
2747 ++FPRCnt;
2748 break;
2749 }
2750
2751 if (GPRCnt > 6)
2752 return false;
2753
2754 if (FPRCnt > 8)
2755 return false;
2756 }
2757
2758 static const MCPhysReg GPR32ArgRegs[] = {
2759 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2760 };
2761 static const MCPhysReg GPR64ArgRegs[] = {
2762 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2763 };
2764 static const MCPhysReg XMMArgRegs[] = {
2765 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2766 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2767 };
2768
2769 unsigned GPRIdx = 0;
2770 unsigned FPRIdx = 0;
2771 for (auto const &Arg : F->args()) {
2772 MVT VT = TLI.getSimpleValueType(Arg.getType());
2773 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2774 unsigned SrcReg;
2775 switch (VT.SimpleTy) {
2776 default: llvm_unreachable("Unexpected value type.");
2777 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2778 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2779 case MVT::f32: // fall-through
2780 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2781 }
2782 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2783 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2784 // Without this, EmitLiveInCopies may eliminate the livein if its only
2785 // use is a bitcast (which isn't turned into an instruction).
2786 unsigned ResultReg = createResultReg(RC);
2787 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2788 TII.get(TargetOpcode::COPY), ResultReg)
2789 .addReg(DstReg, getKillRegState(true));
2790 updateValueMap(&Arg, ResultReg);
2791 }
2792 return true;
2793}
2794
2795static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2796 CallingConv::ID CC,
2797 ImmutableCallSite *CS) {
2798 if (Subtarget->is64Bit())
2799 return 0;
2800 if (Subtarget->getTargetTriple().isOSMSVCRT())
2801 return 0;
2802 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2803 CC == CallingConv::HiPE)
2804 return 0;
2805 if (CS && !CS->paramHasAttr(1, Attribute::StructRet))
2806 return 0;
2807 if (CS && CS->paramHasAttr(1, Attribute::InReg))
2808 return 0;
2809 return 4;
2810}
2811
2812bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2813 auto &OutVals = CLI.OutVals;
2814 auto &OutFlags = CLI.OutFlags;
2815 auto &OutRegs = CLI.OutRegs;
2816 auto &Ins = CLI.Ins;
2817 auto &InRegs = CLI.InRegs;
2818 CallingConv::ID CC = CLI.CallConv;
2819 bool &IsTailCall = CLI.IsTailCall;
2820 bool IsVarArg = CLI.IsVarArg;
2821 const Value *Callee = CLI.Callee;
2822 const char *SymName = CLI.SymName;
2823
2824 bool Is64Bit = Subtarget->is64Bit();
2825 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
2826
2827 // Handle only C, fastcc, and webkit_js calling conventions for now.
2828 switch (CC) {
2829 default: return false;
2830 case CallingConv::C:
2831 case CallingConv::Fast:
2832 case CallingConv::WebKit_JS:
2833 case CallingConv::X86_FastCall:
2834 case CallingConv::X86_64_Win64:
2835 case CallingConv::X86_64_SysV:
2836 break;
2837 }
2838
2839 // Allow SelectionDAG isel to handle tail calls.
2840 if (IsTailCall)
2841 return false;
2842
2843 // fastcc with -tailcallopt is intended to provide a guaranteed
2844 // tail call optimization. Fastisel doesn't know how to do that.
2845 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2846 return false;
2847
2848 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2849 // x86-32. Special handling for x86-64 is implemented.
2850 if (IsVarArg && IsWin64)
2851 return false;
2852
2853 // Don't know about inalloca yet.
2854 if (CLI.CS && CLI.CS->hasInAllocaArgument())
2855 return false;
2856
2857 // Fast-isel doesn't know about callee-pop yet.
2858 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
2859 TM.Options.GuaranteedTailCallOpt))
2860 return false;
2861
2862 SmallVector<MVT, 16> OutVTs;
2863 SmallVector<unsigned, 16> ArgRegs;
2864
2865 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
2866 // instruction. This is safe because it is common to all FastISel supported
2867 // calling conventions on x86.
2868 for (int i = 0, e = OutVals.size(); i != e; ++i) {
2869 Value *&Val = OutVals[i];
2870 ISD::ArgFlagsTy Flags = OutFlags[i];
2871 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
2872 if (CI->getBitWidth() < 32) {
2873 if (Flags.isSExt())
2874 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
2875 else
2876 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
2877 }
2878 }
2879
2880 // Passing bools around ends up doing a trunc to i1 and passing it.
2881 // Codegen this as an argument + "and 1".
2882 MVT VT;
2883 auto *TI = dyn_cast<TruncInst>(Val);
2884 unsigned ResultReg;
2885 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
2886 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
2887 TI->hasOneUse()) {
2888 Value *PrevVal = TI->getOperand(0);
2889 ResultReg = getRegForValue(PrevVal);
2890
2891 if (!ResultReg)
2892 return false;
2893
2894 if (!isTypeLegal(PrevVal->getType(), VT))
2895 return false;
2896
2897 ResultReg =
2898 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
2899 } else {
2900 if (!isTypeLegal(Val->getType(), VT))
2901 return false;
2902 ResultReg = getRegForValue(Val);
2903 }
2904
2905 if (!ResultReg)
2906 return false;
2907
2908 ArgRegs.push_back(ResultReg);
2909 OutVTs.push_back(VT);
2910 }
2911
2912 // Analyze operands of the call, assigning locations to each operand.
2913 SmallVector<CCValAssign, 16> ArgLocs;
2914 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
2915
2916 // Allocate shadow area for Win64
2917 if (IsWin64)
2918 CCInfo.AllocateStack(32, 8);
2919
2920 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
2921
2922 // Get a count of how many bytes are to be pushed on the stack.
2923 unsigned NumBytes = CCInfo.getNextStackOffset();
2924
2925 // Issue CALLSEQ_START
2926 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2927 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
Michael Kuperstein13fbd452015-02-01 16:56:04 +00002928 .addImm(NumBytes).addImm(0);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002929
2930 // Walk the register/memloc assignments, inserting copies/loads.
Eric Christophera1c535b2015-02-02 23:03:45 +00002931 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002932 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2933 CCValAssign const &VA = ArgLocs[i];
2934 const Value *ArgVal = OutVals[VA.getValNo()];
2935 MVT ArgVT = OutVTs[VA.getValNo()];
2936
2937 if (ArgVT == MVT::x86mmx)
2938 return false;
2939
2940 unsigned ArgReg = ArgRegs[VA.getValNo()];
2941
2942 // Promote the value if needed.
2943 switch (VA.getLocInfo()) {
2944 case CCValAssign::Full: break;
2945 case CCValAssign::SExt: {
2946 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2947 "Unexpected extend");
2948 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2949 ArgVT, ArgReg);
2950 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2951 ArgVT = VA.getLocVT();
2952 break;
2953 }
2954 case CCValAssign::ZExt: {
2955 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2956 "Unexpected extend");
2957 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2958 ArgVT, ArgReg);
2959 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2960 ArgVT = VA.getLocVT();
2961 break;
2962 }
2963 case CCValAssign::AExt: {
2964 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2965 "Unexpected extend");
2966 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
2967 ArgVT, ArgReg);
2968 if (!Emitted)
2969 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2970 ArgVT, ArgReg);
2971 if (!Emitted)
2972 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2973 ArgVT, ArgReg);
2974
2975 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2976 ArgVT = VA.getLocVT();
2977 break;
2978 }
2979 case CCValAssign::BCvt: {
2980 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
2981 /*TODO: Kill=*/false);
2982 assert(ArgReg && "Failed to emit a bitcast!");
2983 ArgVT = VA.getLocVT();
2984 break;
2985 }
2986 case CCValAssign::VExt:
2987 // VExt has not been implemented, so this should be impossible to reach
2988 // for now. However, fallback to Selection DAG isel once implemented.
2989 return false;
2990 case CCValAssign::AExtUpper:
2991 case CCValAssign::SExtUpper:
2992 case CCValAssign::ZExtUpper:
2993 case CCValAssign::FPExt:
2994 llvm_unreachable("Unexpected loc info!");
2995 case CCValAssign::Indirect:
2996 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2997 // support this.
2998 return false;
2999 }
3000
3001 if (VA.isRegLoc()) {
3002 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3003 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3004 OutRegs.push_back(VA.getLocReg());
3005 } else {
3006 assert(VA.isMemLoc());
3007
3008 // Don't emit stores for undef values.
3009 if (isa<UndefValue>(ArgVal))
3010 continue;
3011
3012 unsigned LocMemOffset = VA.getLocMemOffset();
3013 X86AddressMode AM;
3014 AM.Base.Reg = RegInfo->getStackRegister();
3015 AM.Disp = LocMemOffset;
3016 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3017 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3018 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3019 MachinePointerInfo::getStack(LocMemOffset), MachineMemOperand::MOStore,
3020 ArgVT.getStoreSize(), Alignment);
3021 if (Flags.isByVal()) {
3022 X86AddressMode SrcAM;
3023 SrcAM.Base.Reg = ArgReg;
3024 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3025 return false;
3026 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3027 // If this is a really simple value, emit this with the Value* version
3028 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3029 // as it can cause us to reevaluate the argument.
3030 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3031 return false;
3032 } else {
3033 bool ValIsKill = hasTrivialKill(ArgVal);
3034 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3035 return false;
3036 }
3037 }
3038 }
3039
3040 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3041 // GOT pointer.
3042 if (Subtarget->isPICStyleGOT()) {
3043 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3044 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3045 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3046 }
3047
3048 if (Is64Bit && IsVarArg && !IsWin64) {
3049 // From AMD64 ABI document:
3050 // For calls that may call functions that use varargs or stdargs
3051 // (prototype-less calls or calls to functions containing ellipsis (...) in
3052 // the declaration) %al is used as hidden argument to specify the number
3053 // of SSE registers used. The contents of %al do not need to match exactly
3054 // the number of registers, but must be an ubound on the number of SSE
3055 // registers used and is in the range 0 - 8 inclusive.
3056
3057 // Count the number of XMM registers allocated.
3058 static const MCPhysReg XMMArgRegs[] = {
3059 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3060 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3061 };
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003062 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003063 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3064 && "SSE registers cannot be used when SSE is disabled");
3065 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3066 X86::AL).addImm(NumXMMRegs);
3067 }
3068
3069 // Materialize callee address in a register. FIXME: GV address can be
3070 // handled with a CALLpcrel32 instead.
3071 X86AddressMode CalleeAM;
3072 if (!X86SelectCallAddress(Callee, CalleeAM))
3073 return false;
3074
3075 unsigned CalleeOp = 0;
3076 const GlobalValue *GV = nullptr;
3077 if (CalleeAM.GV != nullptr) {
3078 GV = CalleeAM.GV;
3079 } else if (CalleeAM.Base.Reg != 0) {
3080 CalleeOp = CalleeAM.Base.Reg;
3081 } else
3082 return false;
3083
3084 // Issue the call.
3085 MachineInstrBuilder MIB;
3086 if (CalleeOp) {
3087 // Register-indirect call.
3088 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3089 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3090 .addReg(CalleeOp);
3091 } else {
3092 // Direct call.
3093 assert(GV && "Not a direct call");
3094 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3095
3096 // See if we need any target-specific flags on the GV operand.
3097 unsigned char OpFlags = 0;
3098
3099 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3100 // external symbols most go through the PLT in PIC mode. If the symbol
3101 // has hidden or protected visibility, or if it is static or local, then
3102 // we don't need to use the PLT - we can directly call it.
3103 if (Subtarget->isTargetELF() &&
3104 TM.getRelocationModel() == Reloc::PIC_ &&
3105 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3106 OpFlags = X86II::MO_PLT;
3107 } else if (Subtarget->isPICStyleStubAny() &&
3108 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3109 (!Subtarget->getTargetTriple().isMacOSX() ||
3110 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3111 // PC-relative references to external symbols should go through $stub,
3112 // unless we're building with the leopard linker or later, which
3113 // automatically synthesizes these stubs.
3114 OpFlags = X86II::MO_DARWIN_STUB;
3115 }
3116
3117 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3118 if (SymName)
3119 MIB.addExternalSymbol(SymName, OpFlags);
3120 else
3121 MIB.addGlobalAddress(GV, 0, OpFlags);
3122 }
3123
3124 // Add a register mask operand representing the call-preserved registers.
3125 // Proper defs for return values will be added by setPhysRegsDeadExcept().
Eric Christopher9deb75d2015-03-11 22:42:13 +00003126 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003127
3128 // Add an implicit use GOT pointer in EBX.
3129 if (Subtarget->isPICStyleGOT())
3130 MIB.addReg(X86::EBX, RegState::Implicit);
3131
3132 if (Is64Bit && IsVarArg && !IsWin64)
3133 MIB.addReg(X86::AL, RegState::Implicit);
3134
3135 // Add implicit physical register uses to the call.
3136 for (auto Reg : OutRegs)
3137 MIB.addReg(Reg, RegState::Implicit);
3138
3139 // Issue CALLSEQ_END
3140 unsigned NumBytesForCalleeToPop =
3141 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
3142 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3143 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3144 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3145
3146 // Now handle call return values.
3147 SmallVector<CCValAssign, 16> RVLocs;
3148 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3149 CLI.RetTy->getContext());
3150 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3151
3152 // Copy all of the result registers out of their specified physreg.
3153 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3154 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3155 CCValAssign &VA = RVLocs[i];
3156 EVT CopyVT = VA.getValVT();
3157 unsigned CopyReg = ResultReg + i;
3158
3159 // If this is x86-64, and we disabled SSE, we can't return FP values
3160 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3161 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3162 report_fatal_error("SSE register return with SSE disabled");
3163 }
3164
3165 // If we prefer to use the value in xmm registers, copy it out as f80 and
3166 // use a truncate to move it from fp stack reg to xmm reg.
3167 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3168 isScalarFPTypeInSSEReg(VA.getValVT())) {
3169 CopyVT = MVT::f80;
3170 CopyReg = createResultReg(&X86::RFP80RegClass);
3171 }
3172
3173 // Copy out the result.
3174 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3175 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3176 InRegs.push_back(VA.getLocReg());
3177
3178 // Round the f80 to the right size, which also moves it to the appropriate
3179 // xmm register. This is accomplished by storing the f80 value in memory
3180 // and then loading it back.
3181 if (CopyVT != VA.getValVT()) {
3182 EVT ResVT = VA.getValVT();
3183 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3184 unsigned MemSize = ResVT.getSizeInBits()/8;
3185 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3186 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3187 TII.get(Opc)), FI)
3188 .addReg(CopyReg);
3189 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3190 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3191 TII.get(Opc), ResultReg + i), FI);
3192 }
3193 }
3194
3195 CLI.ResultReg = ResultReg;
3196 CLI.NumResultRegs = RVLocs.size();
3197 CLI.Call = MIB;
3198
3199 return true;
3200}
3201
3202bool
3203X86FastISel::fastSelectInstruction(const Instruction *I) {
3204 switch (I->getOpcode()) {
3205 default: break;
3206 case Instruction::Load:
3207 return X86SelectLoad(I);
3208 case Instruction::Store:
3209 return X86SelectStore(I);
3210 case Instruction::Ret:
3211 return X86SelectRet(I);
3212 case Instruction::ICmp:
3213 case Instruction::FCmp:
3214 return X86SelectCmp(I);
3215 case Instruction::ZExt:
3216 return X86SelectZExt(I);
3217 case Instruction::Br:
3218 return X86SelectBranch(I);
3219 case Instruction::LShr:
3220 case Instruction::AShr:
3221 case Instruction::Shl:
3222 return X86SelectShift(I);
3223 case Instruction::SDiv:
3224 case Instruction::UDiv:
3225 case Instruction::SRem:
3226 case Instruction::URem:
3227 return X86SelectDivRem(I);
3228 case Instruction::Select:
3229 return X86SelectSelect(I);
3230 case Instruction::Trunc:
3231 return X86SelectTrunc(I);
3232 case Instruction::FPExt:
3233 return X86SelectFPExt(I);
3234 case Instruction::FPTrunc:
3235 return X86SelectFPTrunc(I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00003236 case Instruction::SIToFP:
3237 return X86SelectSIToFP(I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003238 case Instruction::IntToPtr: // Deliberate fall-through.
3239 case Instruction::PtrToInt: {
3240 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType());
3241 EVT DstVT = TLI.getValueType(I->getType());
3242 if (DstVT.bitsGT(SrcVT))
3243 return X86SelectZExt(I);
3244 if (DstVT.bitsLT(SrcVT))
3245 return X86SelectTrunc(I);
3246 unsigned Reg = getRegForValue(I->getOperand(0));
3247 if (Reg == 0) return false;
3248 updateValueMap(I, Reg);
3249 return true;
3250 }
3251 }
3252
3253 return false;
3254}
3255
3256unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3257 if (VT > MVT::i64)
3258 return 0;
3259
3260 uint64_t Imm = CI->getZExtValue();
3261 if (Imm == 0) {
3262 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3263 switch (VT.SimpleTy) {
3264 default: llvm_unreachable("Unexpected value type");
3265 case MVT::i1:
3266 case MVT::i8:
3267 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3268 X86::sub_8bit);
3269 case MVT::i16:
3270 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3271 X86::sub_16bit);
3272 case MVT::i32:
3273 return SrcReg;
3274 case MVT::i64: {
3275 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3276 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3277 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3278 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3279 return ResultReg;
3280 }
3281 }
3282 }
3283
3284 unsigned Opc = 0;
3285 switch (VT.SimpleTy) {
3286 default: llvm_unreachable("Unexpected value type");
3287 case MVT::i1: VT = MVT::i8; // fall-through
3288 case MVT::i8: Opc = X86::MOV8ri; break;
3289 case MVT::i16: Opc = X86::MOV16ri; break;
3290 case MVT::i32: Opc = X86::MOV32ri; break;
3291 case MVT::i64: {
3292 if (isUInt<32>(Imm))
3293 Opc = X86::MOV32ri;
3294 else if (isInt<32>(Imm))
3295 Opc = X86::MOV64ri32;
3296 else
3297 Opc = X86::MOV64ri;
3298 break;
3299 }
3300 }
3301 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3302 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3303 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3304 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3305 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3306 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3307 return ResultReg;
3308 }
3309 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3310}
3311
3312unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3313 if (CFP->isNullValue())
3314 return fastMaterializeFloatZero(CFP);
3315
3316 // Can't handle alternate code models yet.
3317 CodeModel::Model CM = TM.getCodeModel();
3318 if (CM != CodeModel::Small && CM != CodeModel::Large)
3319 return 0;
3320
3321 // Get opcode and regclass of the output for the given load instruction.
3322 unsigned Opc = 0;
3323 const TargetRegisterClass *RC = nullptr;
3324 switch (VT.SimpleTy) {
3325 default: return 0;
3326 case MVT::f32:
3327 if (X86ScalarSSEf32) {
3328 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3329 RC = &X86::FR32RegClass;
3330 } else {
3331 Opc = X86::LD_Fp32m;
3332 RC = &X86::RFP32RegClass;
3333 }
3334 break;
3335 case MVT::f64:
3336 if (X86ScalarSSEf64) {
3337 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3338 RC = &X86::FR64RegClass;
3339 } else {
3340 Opc = X86::LD_Fp64m;
3341 RC = &X86::RFP64RegClass;
3342 }
3343 break;
3344 case MVT::f80:
3345 // No f80 support yet.
3346 return 0;
3347 }
3348
3349 // MachineConstantPool wants an explicit alignment.
3350 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3351 if (Align == 0) {
3352 // Alignment of vector types. FIXME!
3353 Align = DL.getTypeAllocSize(CFP->getType());
3354 }
3355
3356 // x86-32 PIC requires a PIC base register for constant pools.
3357 unsigned PICBase = 0;
3358 unsigned char OpFlag = 0;
3359 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3360 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3361 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3362 } else if (Subtarget->isPICStyleGOT()) {
3363 OpFlag = X86II::MO_GOTOFF;
3364 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3365 } else if (Subtarget->isPICStyleRIPRel() &&
3366 TM.getCodeModel() == CodeModel::Small) {
3367 PICBase = X86::RIP;
3368 }
3369
3370 // Create the load from the constant pool.
3371 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3372 unsigned ResultReg = createResultReg(RC);
3373
3374 if (CM == CodeModel::Large) {
3375 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3376 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3377 AddrReg)
3378 .addConstantPoolIndex(CPI, 0, OpFlag);
3379 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3380 TII.get(Opc), ResultReg);
3381 addDirectMem(MIB, AddrReg);
3382 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3383 MachinePointerInfo::getConstantPool(), MachineMemOperand::MOLoad,
3384 TM.getDataLayout()->getPointerSize(), Align);
3385 MIB->addMemOperand(*FuncInfo.MF, MMO);
3386 return ResultReg;
3387 }
3388
3389 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3390 TII.get(Opc), ResultReg),
3391 CPI, PICBase, OpFlag);
3392 return ResultReg;
3393}
3394
3395unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3396 // Can't handle alternate code models yet.
3397 if (TM.getCodeModel() != CodeModel::Small)
3398 return 0;
3399
3400 // Materialize addresses with LEA/MOV instructions.
3401 X86AddressMode AM;
3402 if (X86SelectAddress(GV, AM)) {
3403 // If the expression is just a basereg, then we're done, otherwise we need
3404 // to emit an LEA.
3405 if (AM.BaseType == X86AddressMode::RegBase &&
3406 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3407 return AM.Base.Reg;
3408
3409 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3410 if (TM.getRelocationModel() == Reloc::Static &&
3411 TLI.getPointerTy() == MVT::i64) {
3412 // The displacement code could be more than 32 bits away so we need to use
3413 // an instruction with a 64 bit immediate
3414 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3415 ResultReg)
3416 .addGlobalAddress(GV);
3417 } else {
3418 unsigned Opc = TLI.getPointerTy() == MVT::i32
3419 ? (Subtarget->isTarget64BitILP32()
3420 ? X86::LEA64_32r : X86::LEA32r)
3421 : X86::LEA64r;
3422 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3423 TII.get(Opc), ResultReg), AM);
3424 }
3425 return ResultReg;
3426 }
3427 return 0;
3428}
3429
3430unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
3431 EVT CEVT = TLI.getValueType(C->getType(), true);
3432
3433 // Only handle simple types.
3434 if (!CEVT.isSimple())
3435 return 0;
3436 MVT VT = CEVT.getSimpleVT();
3437
3438 if (const auto *CI = dyn_cast<ConstantInt>(C))
3439 return X86MaterializeInt(CI, VT);
3440 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3441 return X86MaterializeFP(CFP, VT);
3442 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3443 return X86MaterializeGV(GV, VT);
3444
3445 return 0;
3446}
3447
3448unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3449 // Fail on dynamic allocas. At this point, getRegForValue has already
3450 // checked its CSE maps, so if we're here trying to handle a dynamic
3451 // alloca, we're not going to succeed. X86SelectAddress has a
3452 // check for dynamic allocas, because it's called directly from
3453 // various places, but targetMaterializeAlloca also needs a check
3454 // in order to avoid recursion between getRegForValue,
3455 // X86SelectAddrss, and targetMaterializeAlloca.
3456 if (!FuncInfo.StaticAllocaMap.count(C))
3457 return 0;
3458 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3459
3460 X86AddressMode AM;
3461 if (!X86SelectAddress(C, AM))
3462 return 0;
3463 unsigned Opc = TLI.getPointerTy() == MVT::i32
3464 ? (Subtarget->isTarget64BitILP32()
3465 ? X86::LEA64_32r : X86::LEA32r)
3466 : X86::LEA64r;
3467 const TargetRegisterClass* RC = TLI.getRegClassFor(TLI.getPointerTy());
3468 unsigned ResultReg = createResultReg(RC);
3469 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3470 TII.get(Opc), ResultReg), AM);
3471 return ResultReg;
3472}
3473
3474unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3475 MVT VT;
3476 if (!isTypeLegal(CF->getType(), VT))
3477 return 0;
3478
3479 // Get opcode and regclass for the given zero.
3480 unsigned Opc = 0;
3481 const TargetRegisterClass *RC = nullptr;
3482 switch (VT.SimpleTy) {
3483 default: return 0;
3484 case MVT::f32:
3485 if (X86ScalarSSEf32) {
3486 Opc = X86::FsFLD0SS;
3487 RC = &X86::FR32RegClass;
3488 } else {
3489 Opc = X86::LD_Fp032;
3490 RC = &X86::RFP32RegClass;
3491 }
3492 break;
3493 case MVT::f64:
3494 if (X86ScalarSSEf64) {
3495 Opc = X86::FsFLD0SD;
3496 RC = &X86::FR64RegClass;
3497 } else {
3498 Opc = X86::LD_Fp064;
3499 RC = &X86::RFP64RegClass;
3500 }
3501 break;
3502 case MVT::f80:
3503 // No f80 support yet.
3504 return 0;
3505 }
3506
3507 unsigned ResultReg = createResultReg(RC);
3508 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3509 return ResultReg;
3510}
3511
3512
3513bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3514 const LoadInst *LI) {
3515 const Value *Ptr = LI->getPointerOperand();
3516 X86AddressMode AM;
3517 if (!X86SelectAddress(Ptr, AM))
3518 return false;
3519
3520 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3521
3522 unsigned Size = DL.getTypeAllocSize(LI->getType());
3523 unsigned Alignment = LI->getAlignment();
3524
3525 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3526 Alignment = DL.getABITypeAlignment(LI->getType());
3527
3528 SmallVector<MachineOperand, 8> AddrOps;
3529 AM.getFullAddress(AddrOps);
3530
3531 MachineInstr *Result =
3532 XII.foldMemoryOperandImpl(*FuncInfo.MF, MI, OpNo, AddrOps,
3533 Size, Alignment, /*AllowCommute=*/true);
3534 if (!Result)
3535 return false;
3536
Pete Cooperd31583d2015-05-06 21:37:19 +00003537 // The index register could be in the wrong register class. Unfortunately,
3538 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3539 // to just look at OpNo + the offset to the index reg. We actually need to
3540 // scan the instruction to find the index reg and see if its the correct reg
3541 // class.
3542 for (MIOperands MO(Result); MO.isValid(); ++MO) {
3543 if (!MO->isReg() || MO->isDef() || MO->getReg() != AM.IndexReg)
3544 continue;
3545 // Found the index reg, now try to rewrite it.
3546 unsigned OpNo = MO.getOperandNo();
3547 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
3548 MO->getReg(), OpNo);
3549 if (IndexReg == MO->getReg())
3550 continue;
3551 MO->setReg(IndexReg);
3552 }
3553
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003554 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
3555 FuncInfo.MBB->insert(FuncInfo.InsertPt, Result);
3556 MI->eraseFromParent();
3557 return true;
3558}
3559
3560
3561namespace llvm {
3562 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3563 const TargetLibraryInfo *libInfo) {
3564 return new X86FastISel(funcInfo, libInfo);
3565 }
3566}