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