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