1 //===-- FastISel.cpp - Implementation of the FastISel class ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the FastISel class.
11 //
12 // "Fast" instruction selection is designed to emit very poor code quickly.
13 // Also, it is not designed to be able to do much lowering, so most illegal
14 // types (e.g. i64 on 32-bit targets) and operations are not supported.  It is
15 // also not intended to be able to do much optimization, except in a few cases
16 // where doing optimizations reduces overall compile time.  For example, folding
17 // constants into immediate fields is often done, because it's cheap and it
18 // reduces the number of instructions later phases have to examine.
19 //
20 // "Fast" instruction selection is able to fail gracefully and transfer
21 // control to the SelectionDAG selector for operations that it doesn't
22 // support.  In many cases, this allows us to avoid duplicating a lot of
23 // the complicated lowering logic that SelectionDAG currently has.
24 //
25 // The intended use for "fast" instruction selection is "-O0" mode
26 // compilation, where the quality of the generated code is irrelevant when
27 // weighed against the speed at which the code can be generated.  Also,
28 // at -O0, the LLVM optimizers are not running, and this makes the
29 // compile time of codegen a much higher portion of the overall compile
30 // time.  Despite its limitations, "fast" instruction selection is able to
31 // handle enough code on its own to provide noticeable overall speedups
32 // in -O0 compiles.
33 //
34 // Basic operations are supported in a target-independent way, by reading
35 // the same instruction descriptions that the SelectionDAG selector reads,
36 // and identifying simple arithmetic operations that can be directly selected
37 // from simple operators.  More complicated operations currently require
38 // target-specific code.
39 //
40 //===----------------------------------------------------------------------===//
41 
42 #include "llvm/CodeGen/Analysis.h"
43 #include "llvm/ADT/Optional.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/Analysis/BranchProbabilityInfo.h"
46 #include "llvm/Analysis/Loads.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/CodeGen/Analysis.h"
49 #include "llvm/CodeGen/FastISel.h"
50 #include "llvm/CodeGen/FunctionLoweringInfo.h"
51 #include "llvm/CodeGen/MachineFrameInfo.h"
52 #include "llvm/CodeGen/MachineInstrBuilder.h"
53 #include "llvm/CodeGen/MachineModuleInfo.h"
54 #include "llvm/CodeGen/MachineRegisterInfo.h"
55 #include "llvm/CodeGen/StackMaps.h"
56 #include "llvm/IR/DataLayout.h"
57 #include "llvm/IR/DebugInfo.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/GlobalVariable.h"
60 #include "llvm/IR/Instructions.h"
61 #include "llvm/IR/IntrinsicInst.h"
62 #include "llvm/IR/Mangler.h"
63 #include "llvm/IR/Operator.h"
64 #include "llvm/Support/Debug.h"
65 #include "llvm/Support/ErrorHandling.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Target/TargetInstrInfo.h"
68 #include "llvm/Target/TargetLowering.h"
69 #include "llvm/Target/TargetMachine.h"
70 #include "llvm/Target/TargetSubtargetInfo.h"
71 using namespace llvm;
72 
73 #define DEBUG_TYPE "isel"
74 
75 STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
76                                          "target-independent selector");
77 STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
78                                     "target-specific selector");
79 STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
80 
81 void FastISel::ArgListEntry::setAttributes(ImmutableCallSite *CS,
82                                            unsigned AttrIdx) {
83   IsSExt = CS->paramHasAttr(AttrIdx, Attribute::SExt);
84   IsZExt = CS->paramHasAttr(AttrIdx, Attribute::ZExt);
85   IsInReg = CS->paramHasAttr(AttrIdx, Attribute::InReg);
86   IsSRet = CS->paramHasAttr(AttrIdx, Attribute::StructRet);
87   IsNest = CS->paramHasAttr(AttrIdx, Attribute::Nest);
88   IsByVal = CS->paramHasAttr(AttrIdx, Attribute::ByVal);
89   IsInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca);
90   IsReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned);
91   Alignment = CS->getParamAlignment(AttrIdx);
92 }
93 
94 /// Set the current block to which generated machine instructions will be
95 /// appended, and clear the local CSE map.
96 void FastISel::startNewBlock() {
97   LocalValueMap.clear();
98 
99   // Instructions are appended to FuncInfo.MBB. If the basic block already
100   // contains labels or copies, use the last instruction as the last local
101   // value.
102   EmitStartPt = nullptr;
103   if (!FuncInfo.MBB->empty())
104     EmitStartPt = &FuncInfo.MBB->back();
105   LastLocalValue = EmitStartPt;
106 }
107 
108 bool FastISel::lowerArguments() {
109   if (!FuncInfo.CanLowerReturn)
110     // Fallback to SDISel argument lowering code to deal with sret pointer
111     // parameter.
112     return false;
113 
114   if (!fastLowerArguments())
115     return false;
116 
117   // Enter arguments into ValueMap for uses in non-entry BBs.
118   for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
119                                     E = FuncInfo.Fn->arg_end();
120        I != E; ++I) {
121     DenseMap<const Value *, unsigned>::iterator VI = LocalValueMap.find(&*I);
122     assert(VI != LocalValueMap.end() && "Missed an argument?");
123     FuncInfo.ValueMap[&*I] = VI->second;
124   }
125   return true;
126 }
127 
128 void FastISel::flushLocalValueMap() {
129   LocalValueMap.clear();
130   LastLocalValue = EmitStartPt;
131   recomputeInsertPt();
132   SavedInsertPt = FuncInfo.InsertPt;
133 }
134 
135 bool FastISel::hasTrivialKill(const Value *V) {
136   // Don't consider constants or arguments to have trivial kills.
137   const Instruction *I = dyn_cast<Instruction>(V);
138   if (!I)
139     return false;
140 
141   // No-op casts are trivially coalesced by fast-isel.
142   if (const auto *Cast = dyn_cast<CastInst>(I))
143     if (Cast->isNoopCast(DL.getIntPtrType(Cast->getContext())) &&
144         !hasTrivialKill(Cast->getOperand(0)))
145       return false;
146 
147   // Even the value might have only one use in the LLVM IR, it is possible that
148   // FastISel might fold the use into another instruction and now there is more
149   // than one use at the Machine Instruction level.
150   unsigned Reg = lookUpRegForValue(V);
151   if (Reg && !MRI.use_empty(Reg))
152     return false;
153 
154   // GEPs with all zero indices are trivially coalesced by fast-isel.
155   if (const auto *GEP = dyn_cast<GetElementPtrInst>(I))
156     if (GEP->hasAllZeroIndices() && !hasTrivialKill(GEP->getOperand(0)))
157       return false;
158 
159   // Only instructions with a single use in the same basic block are considered
160   // to have trivial kills.
161   return I->hasOneUse() &&
162          !(I->getOpcode() == Instruction::BitCast ||
163            I->getOpcode() == Instruction::PtrToInt ||
164            I->getOpcode() == Instruction::IntToPtr) &&
165          cast<Instruction>(*I->user_begin())->getParent() == I->getParent();
166 }
167 
168 unsigned FastISel::getRegForValue(const Value *V) {
169   EVT RealVT = TLI.getValueType(DL, V->getType(), /*AllowUnknown=*/true);
170   // Don't handle non-simple values in FastISel.
171   if (!RealVT.isSimple())
172     return 0;
173 
174   // Ignore illegal types. We must do this before looking up the value
175   // in ValueMap because Arguments are given virtual registers regardless
176   // of whether FastISel can handle them.
177   MVT VT = RealVT.getSimpleVT();
178   if (!TLI.isTypeLegal(VT)) {
179     // Handle integer promotions, though, because they're common and easy.
180     if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
181       VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
182     else
183       return 0;
184   }
185 
186   // Look up the value to see if we already have a register for it.
187   unsigned Reg = lookUpRegForValue(V);
188   if (Reg)
189     return Reg;
190 
191   // In bottom-up mode, just create the virtual register which will be used
192   // to hold the value. It will be materialized later.
193   if (isa<Instruction>(V) &&
194       (!isa<AllocaInst>(V) ||
195        !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
196     return FuncInfo.InitializeRegForValue(V);
197 
198   SavePoint SaveInsertPt = enterLocalValueArea();
199 
200   // Materialize the value in a register. Emit any instructions in the
201   // local value area.
202   Reg = materializeRegForValue(V, VT);
203 
204   leaveLocalValueArea(SaveInsertPt);
205 
206   return Reg;
207 }
208 
209 unsigned FastISel::materializeConstant(const Value *V, MVT VT) {
210   unsigned Reg = 0;
211   if (const auto *CI = dyn_cast<ConstantInt>(V)) {
212     if (CI->getValue().getActiveBits() <= 64)
213       Reg = fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
214   } else if (isa<AllocaInst>(V))
215     Reg = fastMaterializeAlloca(cast<AllocaInst>(V));
216   else if (isa<ConstantPointerNull>(V))
217     // Translate this as an integer zero so that it can be
218     // local-CSE'd with actual integer zeros.
219     Reg = getRegForValue(
220         Constant::getNullValue(DL.getIntPtrType(V->getContext())));
221   else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
222     if (CF->isNullValue())
223       Reg = fastMaterializeFloatZero(CF);
224     else
225       // Try to emit the constant directly.
226       Reg = fastEmit_f(VT, VT, ISD::ConstantFP, CF);
227 
228     if (!Reg) {
229       // Try to emit the constant by using an integer constant with a cast.
230       const APFloat &Flt = CF->getValueAPF();
231       EVT IntVT = TLI.getPointerTy(DL);
232 
233       uint64_t x[2];
234       uint32_t IntBitWidth = IntVT.getSizeInBits();
235       bool isExact;
236       (void)Flt.convertToInteger(x, IntBitWidth, /*isSigned=*/true,
237                                  APFloat::rmTowardZero, &isExact);
238       if (isExact) {
239         APInt IntVal(IntBitWidth, x);
240 
241         unsigned IntegerReg =
242             getRegForValue(ConstantInt::get(V->getContext(), IntVal));
243         if (IntegerReg != 0)
244           Reg = fastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP, IntegerReg,
245                            /*Kill=*/false);
246       }
247     }
248   } else if (const auto *Op = dyn_cast<Operator>(V)) {
249     if (!selectOperator(Op, Op->getOpcode()))
250       if (!isa<Instruction>(Op) ||
251           !fastSelectInstruction(cast<Instruction>(Op)))
252         return 0;
253     Reg = lookUpRegForValue(Op);
254   } else if (isa<UndefValue>(V)) {
255     Reg = createResultReg(TLI.getRegClassFor(VT));
256     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
257             TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
258   }
259   return Reg;
260 }
261 
262 /// Helper for getRegForValue. This function is called when the value isn't
263 /// already available in a register and must be materialized with new
264 /// instructions.
265 unsigned FastISel::materializeRegForValue(const Value *V, MVT VT) {
266   unsigned Reg = 0;
267   // Give the target-specific code a try first.
268   if (isa<Constant>(V))
269     Reg = fastMaterializeConstant(cast<Constant>(V));
270 
271   // If target-specific code couldn't or didn't want to handle the value, then
272   // give target-independent code a try.
273   if (!Reg)
274     Reg = materializeConstant(V, VT);
275 
276   // Don't cache constant materializations in the general ValueMap.
277   // To do so would require tracking what uses they dominate.
278   if (Reg) {
279     LocalValueMap[V] = Reg;
280     LastLocalValue = MRI.getVRegDef(Reg);
281   }
282   return Reg;
283 }
284 
285 unsigned FastISel::lookUpRegForValue(const Value *V) {
286   // Look up the value to see if we already have a register for it. We
287   // cache values defined by Instructions across blocks, and other values
288   // only locally. This is because Instructions already have the SSA
289   // def-dominates-use requirement enforced.
290   DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(V);
291   if (I != FuncInfo.ValueMap.end())
292     return I->second;
293   return LocalValueMap[V];
294 }
295 
296 void FastISel::updateValueMap(const Value *I, unsigned Reg, unsigned NumRegs) {
297   if (!isa<Instruction>(I)) {
298     LocalValueMap[I] = Reg;
299     return;
300   }
301 
302   unsigned &AssignedReg = FuncInfo.ValueMap[I];
303   if (AssignedReg == 0)
304     // Use the new register.
305     AssignedReg = Reg;
306   else if (Reg != AssignedReg) {
307     // Arrange for uses of AssignedReg to be replaced by uses of Reg.
308     for (unsigned i = 0; i < NumRegs; i++)
309       FuncInfo.RegFixups[AssignedReg + i] = Reg + i;
310 
311     AssignedReg = Reg;
312   }
313 }
314 
315 std::pair<unsigned, bool> FastISel::getRegForGEPIndex(const Value *Idx) {
316   unsigned IdxN = getRegForValue(Idx);
317   if (IdxN == 0)
318     // Unhandled operand. Halt "fast" selection and bail.
319     return std::pair<unsigned, bool>(0, false);
320 
321   bool IdxNIsKill = hasTrivialKill(Idx);
322 
323   // If the index is smaller or larger than intptr_t, truncate or extend it.
324   MVT PtrVT = TLI.getPointerTy(DL);
325   EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
326   if (IdxVT.bitsLT(PtrVT)) {
327     IdxN = fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND, IdxN,
328                       IdxNIsKill);
329     IdxNIsKill = true;
330   } else if (IdxVT.bitsGT(PtrVT)) {
331     IdxN =
332         fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE, IdxN, IdxNIsKill);
333     IdxNIsKill = true;
334   }
335   return std::pair<unsigned, bool>(IdxN, IdxNIsKill);
336 }
337 
338 void FastISel::recomputeInsertPt() {
339   if (getLastLocalValue()) {
340     FuncInfo.InsertPt = getLastLocalValue();
341     FuncInfo.MBB = FuncInfo.InsertPt->getParent();
342     ++FuncInfo.InsertPt;
343   } else
344     FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
345 
346   // Now skip past any EH_LABELs, which must remain at the beginning.
347   while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
348          FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
349     ++FuncInfo.InsertPt;
350 }
351 
352 void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
353                               MachineBasicBlock::iterator E) {
354   assert(I && E && std::distance(I, E) > 0 && "Invalid iterator!");
355   while (I != E) {
356     MachineInstr *Dead = &*I;
357     ++I;
358     Dead->eraseFromParent();
359     ++NumFastIselDead;
360   }
361   recomputeInsertPt();
362 }
363 
364 FastISel::SavePoint FastISel::enterLocalValueArea() {
365   MachineBasicBlock::iterator OldInsertPt = FuncInfo.InsertPt;
366   DebugLoc OldDL = DbgLoc;
367   recomputeInsertPt();
368   DbgLoc = DebugLoc();
369   SavePoint SP = {OldInsertPt, OldDL};
370   return SP;
371 }
372 
373 void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
374   if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
375     LastLocalValue = std::prev(FuncInfo.InsertPt);
376 
377   // Restore the previous insert position.
378   FuncInfo.InsertPt = OldInsertPt.InsertPt;
379   DbgLoc = OldInsertPt.DL;
380 }
381 
382 bool FastISel::selectBinaryOp(const User *I, unsigned ISDOpcode) {
383   EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
384   if (VT == MVT::Other || !VT.isSimple())
385     // Unhandled type. Halt "fast" selection and bail.
386     return false;
387 
388   // We only handle legal types. For example, on x86-32 the instruction
389   // selector contains all of the 64-bit instructions from x86-64,
390   // under the assumption that i64 won't be used if the target doesn't
391   // support it.
392   if (!TLI.isTypeLegal(VT)) {
393     // MVT::i1 is special. Allow AND, OR, or XOR because they
394     // don't require additional zeroing, which makes them easy.
395     if (VT == MVT::i1 && (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
396                           ISDOpcode == ISD::XOR))
397       VT = TLI.getTypeToTransformTo(I->getContext(), VT);
398     else
399       return false;
400   }
401 
402   // Check if the first operand is a constant, and handle it as "ri".  At -O0,
403   // we don't have anything that canonicalizes operand order.
404   if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
405     if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
406       unsigned Op1 = getRegForValue(I->getOperand(1));
407       if (!Op1)
408         return false;
409       bool Op1IsKill = hasTrivialKill(I->getOperand(1));
410 
411       unsigned ResultReg =
412           fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1, Op1IsKill,
413                        CI->getZExtValue(), VT.getSimpleVT());
414       if (!ResultReg)
415         return false;
416 
417       // We successfully emitted code for the given LLVM Instruction.
418       updateValueMap(I, ResultReg);
419       return true;
420     }
421 
422   unsigned Op0 = getRegForValue(I->getOperand(0));
423   if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
424     return false;
425   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
426 
427   // Check if the second operand is a constant and handle it appropriately.
428   if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
429     uint64_t Imm = CI->getSExtValue();
430 
431     // Transform "sdiv exact X, 8" -> "sra X, 3".
432     if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
433         cast<BinaryOperator>(I)->isExact() && isPowerOf2_64(Imm)) {
434       Imm = Log2_64(Imm);
435       ISDOpcode = ISD::SRA;
436     }
437 
438     // Transform "urem x, pow2" -> "and x, pow2-1".
439     if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
440         isPowerOf2_64(Imm)) {
441       --Imm;
442       ISDOpcode = ISD::AND;
443     }
444 
445     unsigned ResultReg = fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0,
446                                       Op0IsKill, Imm, VT.getSimpleVT());
447     if (!ResultReg)
448       return false;
449 
450     // We successfully emitted code for the given LLVM Instruction.
451     updateValueMap(I, ResultReg);
452     return true;
453   }
454 
455   // Check if the second operand is a constant float.
456   if (const auto *CF = dyn_cast<ConstantFP>(I->getOperand(1))) {
457     unsigned ResultReg = fastEmit_rf(VT.getSimpleVT(), VT.getSimpleVT(),
458                                      ISDOpcode, Op0, Op0IsKill, CF);
459     if (ResultReg) {
460       // We successfully emitted code for the given LLVM Instruction.
461       updateValueMap(I, ResultReg);
462       return true;
463     }
464   }
465 
466   unsigned Op1 = getRegForValue(I->getOperand(1));
467   if (!Op1) // Unhandled operand. Halt "fast" selection and bail.
468     return false;
469   bool Op1IsKill = hasTrivialKill(I->getOperand(1));
470 
471   // Now we have both operands in registers. Emit the instruction.
472   unsigned ResultReg = fastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
473                                    ISDOpcode, Op0, Op0IsKill, Op1, Op1IsKill);
474   if (!ResultReg)
475     // Target-specific code wasn't able to find a machine opcode for
476     // the given ISD opcode and type. Halt "fast" selection and bail.
477     return false;
478 
479   // We successfully emitted code for the given LLVM Instruction.
480   updateValueMap(I, ResultReg);
481   return true;
482 }
483 
484 bool FastISel::selectGetElementPtr(const User *I) {
485   unsigned N = getRegForValue(I->getOperand(0));
486   if (!N) // Unhandled operand. Halt "fast" selection and bail.
487     return false;
488   bool NIsKill = hasTrivialKill(I->getOperand(0));
489 
490   // Keep a running tab of the total offset to coalesce multiple N = N + Offset
491   // into a single N = N + TotalOffset.
492   uint64_t TotalOffs = 0;
493   // FIXME: What's a good SWAG number for MaxOffs?
494   uint64_t MaxOffs = 2048;
495   Type *Ty = I->getOperand(0)->getType();
496   MVT VT = TLI.getPointerTy(DL);
497   for (GetElementPtrInst::const_op_iterator OI = I->op_begin() + 1,
498                                             E = I->op_end();
499        OI != E; ++OI) {
500     const Value *Idx = *OI;
501     if (auto *StTy = dyn_cast<StructType>(Ty)) {
502       uint64_t Field = cast<ConstantInt>(Idx)->getZExtValue();
503       if (Field) {
504         // N = N + Offset
505         TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
506         if (TotalOffs >= MaxOffs) {
507           N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
508           if (!N) // Unhandled operand. Halt "fast" selection and bail.
509             return false;
510           NIsKill = true;
511           TotalOffs = 0;
512         }
513       }
514       Ty = StTy->getElementType(Field);
515     } else {
516       if (Ty->isPointerTy()) {
517         // The only pointer type is for the very first index,
518         // therefore the next type is the source element type.
519         Ty = cast<GEPOperator>(I)->getSourceElementType();
520       } else {
521         Ty = cast<SequentialType>(Ty)->getElementType();
522       }
523 
524       // If this is a constant subscript, handle it quickly.
525       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
526         if (CI->isZero())
527           continue;
528         // N = N + Offset
529         uint64_t IdxN = CI->getValue().sextOrTrunc(64).getSExtValue();
530         TotalOffs += DL.getTypeAllocSize(Ty) * IdxN;
531         if (TotalOffs >= MaxOffs) {
532           N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
533           if (!N) // Unhandled operand. Halt "fast" selection and bail.
534             return false;
535           NIsKill = true;
536           TotalOffs = 0;
537         }
538         continue;
539       }
540       if (TotalOffs) {
541         N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
542         if (!N) // Unhandled operand. Halt "fast" selection and bail.
543           return false;
544         NIsKill = true;
545         TotalOffs = 0;
546       }
547 
548       // N = N + Idx * ElementSize;
549       uint64_t ElementSize = DL.getTypeAllocSize(Ty);
550       std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
551       unsigned IdxN = Pair.first;
552       bool IdxNIsKill = Pair.second;
553       if (!IdxN) // Unhandled operand. Halt "fast" selection and bail.
554         return false;
555 
556       if (ElementSize != 1) {
557         IdxN = fastEmit_ri_(VT, ISD::MUL, IdxN, IdxNIsKill, ElementSize, VT);
558         if (!IdxN) // Unhandled operand. Halt "fast" selection and bail.
559           return false;
560         IdxNIsKill = true;
561       }
562       N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
563       if (!N) // Unhandled operand. Halt "fast" selection and bail.
564         return false;
565     }
566   }
567   if (TotalOffs) {
568     N = fastEmit_ri_(VT, ISD::ADD, N, NIsKill, TotalOffs, VT);
569     if (!N) // Unhandled operand. Halt "fast" selection and bail.
570       return false;
571   }
572 
573   // We successfully emitted code for the given LLVM Instruction.
574   updateValueMap(I, N);
575   return true;
576 }
577 
578 bool FastISel::addStackMapLiveVars(SmallVectorImpl<MachineOperand> &Ops,
579                                    const CallInst *CI, unsigned StartIdx) {
580   for (unsigned i = StartIdx, e = CI->getNumArgOperands(); i != e; ++i) {
581     Value *Val = CI->getArgOperand(i);
582     // Check for constants and encode them with a StackMaps::ConstantOp prefix.
583     if (const auto *C = dyn_cast<ConstantInt>(Val)) {
584       Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp));
585       Ops.push_back(MachineOperand::CreateImm(C->getSExtValue()));
586     } else if (isa<ConstantPointerNull>(Val)) {
587       Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp));
588       Ops.push_back(MachineOperand::CreateImm(0));
589     } else if (auto *AI = dyn_cast<AllocaInst>(Val)) {
590       // Values coming from a stack location also require a sepcial encoding,
591       // but that is added later on by the target specific frame index
592       // elimination implementation.
593       auto SI = FuncInfo.StaticAllocaMap.find(AI);
594       if (SI != FuncInfo.StaticAllocaMap.end())
595         Ops.push_back(MachineOperand::CreateFI(SI->second));
596       else
597         return false;
598     } else {
599       unsigned Reg = getRegForValue(Val);
600       if (!Reg)
601         return false;
602       Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false));
603     }
604   }
605   return true;
606 }
607 
608 bool FastISel::selectStackmap(const CallInst *I) {
609   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
610   //                                  [live variables...])
611   assert(I->getCalledFunction()->getReturnType()->isVoidTy() &&
612          "Stackmap cannot return a value.");
613 
614   // The stackmap intrinsic only records the live variables (the arguments
615   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
616   // intrinsic, this won't be lowered to a function call. This means we don't
617   // have to worry about calling conventions and target-specific lowering code.
618   // Instead we perform the call lowering right here.
619   //
620   // CALLSEQ_START(0...)
621   // STACKMAP(id, nbytes, ...)
622   // CALLSEQ_END(0, 0)
623   //
624   SmallVector<MachineOperand, 32> Ops;
625 
626   // Add the <id> and <numBytes> constants.
627   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) &&
628          "Expected a constant integer.");
629   const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos));
630   Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue()));
631 
632   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) &&
633          "Expected a constant integer.");
634   const auto *NumBytes =
635       cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos));
636   Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue()));
637 
638   // Push live variables for the stack map (skipping the first two arguments
639   // <id> and <numBytes>).
640   if (!addStackMapLiveVars(Ops, I, 2))
641     return false;
642 
643   // We are not adding any register mask info here, because the stackmap doesn't
644   // clobber anything.
645 
646   // Add scratch registers as implicit def and early clobber.
647   CallingConv::ID CC = I->getCallingConv();
648   const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC);
649   for (unsigned i = 0; ScratchRegs[i]; ++i)
650     Ops.push_back(MachineOperand::CreateReg(
651         ScratchRegs[i], /*IsDef=*/true, /*IsImp=*/true, /*IsKill=*/false,
652         /*IsDead=*/false, /*IsUndef=*/false, /*IsEarlyClobber=*/true));
653 
654   // Issue CALLSEQ_START
655   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
656   auto Builder =
657       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown));
658   const MCInstrDesc &MCID = Builder.getInstr()->getDesc();
659   for (unsigned I = 0, E = MCID.getNumOperands(); I < E; ++I)
660     Builder.addImm(0);
661 
662   // Issue STACKMAP.
663   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
664                                     TII.get(TargetOpcode::STACKMAP));
665   for (auto const &MO : Ops)
666     MIB.addOperand(MO);
667 
668   // Issue CALLSEQ_END
669   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
670   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
671       .addImm(0)
672       .addImm(0);
673 
674   // Inform the Frame Information that we have a stackmap in this function.
675   FuncInfo.MF->getFrameInfo()->setHasStackMap();
676 
677   return true;
678 }
679 
680 /// \brief Lower an argument list according to the target calling convention.
681 ///
682 /// This is a helper for lowering intrinsics that follow a target calling
683 /// convention or require stack pointer adjustment. Only a subset of the
684 /// intrinsic's operands need to participate in the calling convention.
685 bool FastISel::lowerCallOperands(const CallInst *CI, unsigned ArgIdx,
686                                  unsigned NumArgs, const Value *Callee,
687                                  bool ForceRetVoidTy, CallLoweringInfo &CLI) {
688   ArgListTy Args;
689   Args.reserve(NumArgs);
690 
691   // Populate the argument list.
692   // Attributes for args start at offset 1, after the return attribute.
693   ImmutableCallSite CS(CI);
694   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
695        ArgI != ArgE; ++ArgI) {
696     Value *V = CI->getOperand(ArgI);
697 
698     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
699 
700     ArgListEntry Entry;
701     Entry.Val = V;
702     Entry.Ty = V->getType();
703     Entry.setAttributes(&CS, AttrI);
704     Args.push_back(Entry);
705   }
706 
707   Type *RetTy = ForceRetVoidTy ? Type::getVoidTy(CI->getType()->getContext())
708                                : CI->getType();
709   CLI.setCallee(CI->getCallingConv(), RetTy, Callee, std::move(Args), NumArgs);
710 
711   return lowerCallTo(CLI);
712 }
713 
714 FastISel::CallLoweringInfo &FastISel::CallLoweringInfo::setCallee(
715     const DataLayout &DL, MCContext &Ctx, CallingConv::ID CC, Type *ResultTy,
716     const char *Target, ArgListTy &&ArgsList, unsigned FixedArgs) {
717   SmallString<32> MangledName;
718   Mangler::getNameWithPrefix(MangledName, Target, DL);
719   MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName);
720   return setCallee(CC, ResultTy, Sym, std::move(ArgsList), FixedArgs);
721 }
722 
723 bool FastISel::selectPatchpoint(const CallInst *I) {
724   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
725   //                                                 i32 <numBytes>,
726   //                                                 i8* <target>,
727   //                                                 i32 <numArgs>,
728   //                                                 [Args...],
729   //                                                 [live variables...])
730   CallingConv::ID CC = I->getCallingConv();
731   bool IsAnyRegCC = CC == CallingConv::AnyReg;
732   bool HasDef = !I->getType()->isVoidTy();
733   Value *Callee = I->getOperand(PatchPointOpers::TargetPos)->stripPointerCasts();
734 
735   // Get the real number of arguments participating in the call <numArgs>
736   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos)) &&
737          "Expected a constant integer.");
738   const auto *NumArgsVal =
739       cast<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos));
740   unsigned NumArgs = NumArgsVal->getZExtValue();
741 
742   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
743   // This includes all meta-operands up to but not including CC.
744   unsigned NumMetaOpers = PatchPointOpers::CCPos;
745   assert(I->getNumArgOperands() >= NumMetaOpers + NumArgs &&
746          "Not enough arguments provided to the patchpoint intrinsic");
747 
748   // For AnyRegCC the arguments are lowered later on manually.
749   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
750   CallLoweringInfo CLI;
751   CLI.setIsPatchPoint();
752   if (!lowerCallOperands(I, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC, CLI))
753     return false;
754 
755   assert(CLI.Call && "No call instruction specified.");
756 
757   SmallVector<MachineOperand, 32> Ops;
758 
759   // Add an explicit result reg if we use the anyreg calling convention.
760   if (IsAnyRegCC && HasDef) {
761     assert(CLI.NumResultRegs == 0 && "Unexpected result register.");
762     CLI.ResultReg = createResultReg(TLI.getRegClassFor(MVT::i64));
763     CLI.NumResultRegs = 1;
764     Ops.push_back(MachineOperand::CreateReg(CLI.ResultReg, /*IsDef=*/true));
765   }
766 
767   // Add the <id> and <numBytes> constants.
768   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) &&
769          "Expected a constant integer.");
770   const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos));
771   Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue()));
772 
773   assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) &&
774          "Expected a constant integer.");
775   const auto *NumBytes =
776       cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos));
777   Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue()));
778 
779   // Add the call target.
780   if (const auto *C = dyn_cast<IntToPtrInst>(Callee)) {
781     uint64_t CalleeConstAddr =
782       cast<ConstantInt>(C->getOperand(0))->getZExtValue();
783     Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr));
784   } else if (const auto *C = dyn_cast<ConstantExpr>(Callee)) {
785     if (C->getOpcode() == Instruction::IntToPtr) {
786       uint64_t CalleeConstAddr =
787         cast<ConstantInt>(C->getOperand(0))->getZExtValue();
788       Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr));
789     } else
790       llvm_unreachable("Unsupported ConstantExpr.");
791   } else if (const auto *GV = dyn_cast<GlobalValue>(Callee)) {
792     Ops.push_back(MachineOperand::CreateGA(GV, 0));
793   } else if (isa<ConstantPointerNull>(Callee))
794     Ops.push_back(MachineOperand::CreateImm(0));
795   else
796     llvm_unreachable("Unsupported callee address.");
797 
798   // Adjust <numArgs> to account for any arguments that have been passed on
799   // the stack instead.
800   unsigned NumCallRegArgs = IsAnyRegCC ? NumArgs : CLI.OutRegs.size();
801   Ops.push_back(MachineOperand::CreateImm(NumCallRegArgs));
802 
803   // Add the calling convention
804   Ops.push_back(MachineOperand::CreateImm((unsigned)CC));
805 
806   // Add the arguments we omitted previously. The register allocator should
807   // place these in any free register.
808   if (IsAnyRegCC) {
809     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) {
810       unsigned Reg = getRegForValue(I->getArgOperand(i));
811       if (!Reg)
812         return false;
813       Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false));
814     }
815   }
816 
817   // Push the arguments from the call instruction.
818   for (auto Reg : CLI.OutRegs)
819     Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/false));
820 
821   // Push live variables for the stack map.
822   if (!addStackMapLiveVars(Ops, I, NumMetaOpers + NumArgs))
823     return false;
824 
825   // Push the register mask info.
826   Ops.push_back(MachineOperand::CreateRegMask(
827       TRI.getCallPreservedMask(*FuncInfo.MF, CC)));
828 
829   // Add scratch registers as implicit def and early clobber.
830   const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC);
831   for (unsigned i = 0; ScratchRegs[i]; ++i)
832     Ops.push_back(MachineOperand::CreateReg(
833         ScratchRegs[i], /*IsDef=*/true, /*IsImp=*/true, /*IsKill=*/false,
834         /*IsDead=*/false, /*IsUndef=*/false, /*IsEarlyClobber=*/true));
835 
836   // Add implicit defs (return values).
837   for (auto Reg : CLI.InRegs)
838     Ops.push_back(MachineOperand::CreateReg(Reg, /*IsDef=*/true,
839                                             /*IsImpl=*/true));
840 
841   // Insert the patchpoint instruction before the call generated by the target.
842   MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, CLI.Call, DbgLoc,
843                                     TII.get(TargetOpcode::PATCHPOINT));
844 
845   for (auto &MO : Ops)
846     MIB.addOperand(MO);
847 
848   MIB->setPhysRegsDeadExcept(CLI.InRegs, TRI);
849 
850   // Delete the original call instruction.
851   CLI.Call->eraseFromParent();
852 
853   // Inform the Frame Information that we have a patchpoint in this function.
854   FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
855 
856   if (CLI.NumResultRegs)
857     updateValueMap(I, CLI.ResultReg, CLI.NumResultRegs);
858   return true;
859 }
860 
861 /// Returns an AttributeSet representing the attributes applied to the return
862 /// value of the given call.
863 static AttributeSet getReturnAttrs(FastISel::CallLoweringInfo &CLI) {
864   SmallVector<Attribute::AttrKind, 2> Attrs;
865   if (CLI.RetSExt)
866     Attrs.push_back(Attribute::SExt);
867   if (CLI.RetZExt)
868     Attrs.push_back(Attribute::ZExt);
869   if (CLI.IsInReg)
870     Attrs.push_back(Attribute::InReg);
871 
872   return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
873                            Attrs);
874 }
875 
876 bool FastISel::lowerCallTo(const CallInst *CI, const char *SymName,
877                            unsigned NumArgs) {
878   MCContext &Ctx = MF->getContext();
879   SmallString<32> MangledName;
880   Mangler::getNameWithPrefix(MangledName, SymName, DL);
881   MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName);
882   return lowerCallTo(CI, Sym, NumArgs);
883 }
884 
885 bool FastISel::lowerCallTo(const CallInst *CI, MCSymbol *Symbol,
886                            unsigned NumArgs) {
887   ImmutableCallSite CS(CI);
888 
889   FunctionType *FTy = CS.getFunctionType();
890   Type *RetTy = CS.getType();
891 
892   ArgListTy Args;
893   Args.reserve(NumArgs);
894 
895   // Populate the argument list.
896   // Attributes for args start at offset 1, after the return attribute.
897   for (unsigned ArgI = 0; ArgI != NumArgs; ++ArgI) {
898     Value *V = CI->getOperand(ArgI);
899 
900     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
901 
902     ArgListEntry Entry;
903     Entry.Val = V;
904     Entry.Ty = V->getType();
905     Entry.setAttributes(&CS, ArgI + 1);
906     Args.push_back(Entry);
907   }
908 
909   CallLoweringInfo CLI;
910   CLI.setCallee(RetTy, FTy, Symbol, std::move(Args), CS, NumArgs);
911 
912   return lowerCallTo(CLI);
913 }
914 
915 bool FastISel::lowerCallTo(CallLoweringInfo &CLI) {
916   // Handle the incoming return values from the call.
917   CLI.clearIns();
918   SmallVector<EVT, 4> RetTys;
919   ComputeValueVTs(TLI, DL, CLI.RetTy, RetTys);
920 
921   SmallVector<ISD::OutputArg, 4> Outs;
922   GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, TLI, DL);
923 
924   bool CanLowerReturn = TLI.CanLowerReturn(
925       CLI.CallConv, *FuncInfo.MF, CLI.IsVarArg, Outs, CLI.RetTy->getContext());
926 
927   // FIXME: sret demotion isn't supported yet - bail out.
928   if (!CanLowerReturn)
929     return false;
930 
931   for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
932     EVT VT = RetTys[I];
933     MVT RegisterVT = TLI.getRegisterType(CLI.RetTy->getContext(), VT);
934     unsigned NumRegs = TLI.getNumRegisters(CLI.RetTy->getContext(), VT);
935     for (unsigned i = 0; i != NumRegs; ++i) {
936       ISD::InputArg MyFlags;
937       MyFlags.VT = RegisterVT;
938       MyFlags.ArgVT = VT;
939       MyFlags.Used = CLI.IsReturnValueUsed;
940       if (CLI.RetSExt)
941         MyFlags.Flags.setSExt();
942       if (CLI.RetZExt)
943         MyFlags.Flags.setZExt();
944       if (CLI.IsInReg)
945         MyFlags.Flags.setInReg();
946       CLI.Ins.push_back(MyFlags);
947     }
948   }
949 
950   // Handle all of the outgoing arguments.
951   CLI.clearOuts();
952   for (auto &Arg : CLI.getArgs()) {
953     Type *FinalType = Arg.Ty;
954     if (Arg.IsByVal)
955       FinalType = cast<PointerType>(Arg.Ty)->getElementType();
956     bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
957         FinalType, CLI.CallConv, CLI.IsVarArg);
958 
959     ISD::ArgFlagsTy Flags;
960     if (Arg.IsZExt)
961       Flags.setZExt();
962     if (Arg.IsSExt)
963       Flags.setSExt();
964     if (Arg.IsInReg)
965       Flags.setInReg();
966     if (Arg.IsSRet)
967       Flags.setSRet();
968     if (Arg.IsByVal)
969       Flags.setByVal();
970     if (Arg.IsInAlloca) {
971       Flags.setInAlloca();
972       // Set the byval flag for CCAssignFn callbacks that don't know about
973       // inalloca. This way we can know how many bytes we should've allocated
974       // and how many bytes a callee cleanup function will pop.  If we port
975       // inalloca to more targets, we'll have to add custom inalloca handling in
976       // the various CC lowering callbacks.
977       Flags.setByVal();
978     }
979     if (Arg.IsByVal || Arg.IsInAlloca) {
980       PointerType *Ty = cast<PointerType>(Arg.Ty);
981       Type *ElementTy = Ty->getElementType();
982       unsigned FrameSize = DL.getTypeAllocSize(ElementTy);
983       // For ByVal, alignment should come from FE. BE will guess if this info is
984       // not there, but there are cases it cannot get right.
985       unsigned FrameAlign = Arg.Alignment;
986       if (!FrameAlign)
987         FrameAlign = TLI.getByValTypeAlignment(ElementTy, DL);
988       Flags.setByValSize(FrameSize);
989       Flags.setByValAlign(FrameAlign);
990     }
991     if (Arg.IsNest)
992       Flags.setNest();
993     if (NeedsRegBlock)
994       Flags.setInConsecutiveRegs();
995     unsigned OriginalAlignment = DL.getABITypeAlignment(Arg.Ty);
996     Flags.setOrigAlign(OriginalAlignment);
997 
998     CLI.OutVals.push_back(Arg.Val);
999     CLI.OutFlags.push_back(Flags);
1000   }
1001 
1002   if (!fastLowerCall(CLI))
1003     return false;
1004 
1005   // Set all unused physreg defs as dead.
1006   assert(CLI.Call && "No call instruction specified.");
1007   CLI.Call->setPhysRegsDeadExcept(CLI.InRegs, TRI);
1008 
1009   if (CLI.NumResultRegs && CLI.CS)
1010     updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
1011 
1012   return true;
1013 }
1014 
1015 bool FastISel::lowerCall(const CallInst *CI) {
1016   ImmutableCallSite CS(CI);
1017 
1018   FunctionType *FuncTy = CS.getFunctionType();
1019   Type *RetTy = CS.getType();
1020 
1021   ArgListTy Args;
1022   ArgListEntry Entry;
1023   Args.reserve(CS.arg_size());
1024 
1025   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1026        i != e; ++i) {
1027     Value *V = *i;
1028 
1029     // Skip empty types
1030     if (V->getType()->isEmptyTy())
1031       continue;
1032 
1033     Entry.Val = V;
1034     Entry.Ty = V->getType();
1035 
1036     // Skip the first return-type Attribute to get to params.
1037     Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
1038     Args.push_back(Entry);
1039   }
1040 
1041   // Check if target-independent constraints permit a tail call here.
1042   // Target-dependent constraints are checked within fastLowerCall.
1043   bool IsTailCall = CI->isTailCall();
1044   if (IsTailCall && !isInTailCallPosition(CS, TM))
1045     IsTailCall = false;
1046 
1047   CallLoweringInfo CLI;
1048   CLI.setCallee(RetTy, FuncTy, CI->getCalledValue(), std::move(Args), CS)
1049       .setTailCall(IsTailCall);
1050 
1051   return lowerCallTo(CLI);
1052 }
1053 
1054 bool FastISel::selectCall(const User *I) {
1055   const CallInst *Call = cast<CallInst>(I);
1056 
1057   // Handle simple inline asms.
1058   if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledValue())) {
1059     // If the inline asm has side effects, then make sure that no local value
1060     // lives across by flushing the local value map.
1061     if (IA->hasSideEffects())
1062       flushLocalValueMap();
1063 
1064     // Don't attempt to handle constraints.
1065     if (!IA->getConstraintString().empty())
1066       return false;
1067 
1068     unsigned ExtraInfo = 0;
1069     if (IA->hasSideEffects())
1070       ExtraInfo |= InlineAsm::Extra_HasSideEffects;
1071     if (IA->isAlignStack())
1072       ExtraInfo |= InlineAsm::Extra_IsAlignStack;
1073 
1074     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1075             TII.get(TargetOpcode::INLINEASM))
1076         .addExternalSymbol(IA->getAsmString().c_str())
1077         .addImm(ExtraInfo);
1078     return true;
1079   }
1080 
1081   MachineModuleInfo &MMI = FuncInfo.MF->getMMI();
1082   ComputeUsesVAFloatArgument(*Call, &MMI);
1083 
1084   // Handle intrinsic function calls.
1085   if (const auto *II = dyn_cast<IntrinsicInst>(Call))
1086     return selectIntrinsicCall(II);
1087 
1088   // Usually, it does not make sense to initialize a value,
1089   // make an unrelated function call and use the value, because
1090   // it tends to be spilled on the stack. So, we move the pointer
1091   // to the last local value to the beginning of the block, so that
1092   // all the values which have already been materialized,
1093   // appear after the call. It also makes sense to skip intrinsics
1094   // since they tend to be inlined.
1095   flushLocalValueMap();
1096 
1097   return lowerCall(Call);
1098 }
1099 
1100 bool FastISel::selectIntrinsicCall(const IntrinsicInst *II) {
1101   switch (II->getIntrinsicID()) {
1102   default:
1103     break;
1104   // At -O0 we don't care about the lifetime intrinsics.
1105   case Intrinsic::lifetime_start:
1106   case Intrinsic::lifetime_end:
1107   // The donothing intrinsic does, well, nothing.
1108   case Intrinsic::donothing:
1109     return true;
1110   case Intrinsic::dbg_declare: {
1111     const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
1112     assert(DI->getVariable() && "Missing variable");
1113     if (!FuncInfo.MF->getMMI().hasDebugInfo()) {
1114       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1115       return true;
1116     }
1117 
1118     const Value *Address = DI->getAddress();
1119     if (!Address || isa<UndefValue>(Address)) {
1120       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1121       return true;
1122     }
1123 
1124     unsigned Offset = 0;
1125     Optional<MachineOperand> Op;
1126     if (const auto *Arg = dyn_cast<Argument>(Address))
1127       // Some arguments' frame index is recorded during argument lowering.
1128       Offset = FuncInfo.getArgumentFrameIndex(Arg);
1129     if (Offset)
1130       Op = MachineOperand::CreateFI(Offset);
1131     if (!Op)
1132       if (unsigned Reg = lookUpRegForValue(Address))
1133         Op = MachineOperand::CreateReg(Reg, false);
1134 
1135     // If we have a VLA that has a "use" in a metadata node that's then used
1136     // here but it has no other uses, then we have a problem. E.g.,
1137     //
1138     //   int foo (const int *x) {
1139     //     char a[*x];
1140     //     return 0;
1141     //   }
1142     //
1143     // If we assign 'a' a vreg and fast isel later on has to use the selection
1144     // DAG isel, it will want to copy the value to the vreg. However, there are
1145     // no uses, which goes counter to what selection DAG isel expects.
1146     if (!Op && !Address->use_empty() && isa<Instruction>(Address) &&
1147         (!isa<AllocaInst>(Address) ||
1148          !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
1149       Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address),
1150                                      false);
1151 
1152     if (Op) {
1153       assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
1154              "Expected inlined-at fields to agree");
1155       if (Op->isReg()) {
1156         Op->setIsDebug(true);
1157         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1158                 TII.get(TargetOpcode::DBG_VALUE), false, Op->getReg(), 0,
1159                 DI->getVariable(), DI->getExpression());
1160       } else
1161         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1162                 TII.get(TargetOpcode::DBG_VALUE))
1163             .addOperand(*Op)
1164             .addImm(0)
1165             .addMetadata(DI->getVariable())
1166             .addMetadata(DI->getExpression());
1167     } else {
1168       // We can't yet handle anything else here because it would require
1169       // generating code, thus altering codegen because of debug info.
1170       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1171     }
1172     return true;
1173   }
1174   case Intrinsic::dbg_value: {
1175     // This form of DBG_VALUE is target-independent.
1176     const DbgValueInst *DI = cast<DbgValueInst>(II);
1177     const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1178     const Value *V = DI->getValue();
1179     assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
1180            "Expected inlined-at fields to agree");
1181     if (!V) {
1182       // Currently the optimizer can produce this; insert an undef to
1183       // help debugging.  Probably the optimizer should not do this.
1184       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1185           .addReg(0U)
1186           .addImm(DI->getOffset())
1187           .addMetadata(DI->getVariable())
1188           .addMetadata(DI->getExpression());
1189     } else if (const auto *CI = dyn_cast<ConstantInt>(V)) {
1190       if (CI->getBitWidth() > 64)
1191         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1192             .addCImm(CI)
1193             .addImm(DI->getOffset())
1194             .addMetadata(DI->getVariable())
1195             .addMetadata(DI->getExpression());
1196       else
1197         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1198             .addImm(CI->getZExtValue())
1199             .addImm(DI->getOffset())
1200             .addMetadata(DI->getVariable())
1201             .addMetadata(DI->getExpression());
1202     } else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
1203       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1204           .addFPImm(CF)
1205           .addImm(DI->getOffset())
1206           .addMetadata(DI->getVariable())
1207           .addMetadata(DI->getExpression());
1208     } else if (unsigned Reg = lookUpRegForValue(V)) {
1209       // FIXME: This does not handle register-indirect values at offset 0.
1210       bool IsIndirect = DI->getOffset() != 0;
1211       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, IsIndirect, Reg,
1212               DI->getOffset(), DI->getVariable(), DI->getExpression());
1213     } else {
1214       // We can't yet handle anything else here because it would require
1215       // generating code, thus altering codegen because of debug info.
1216       DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1217     }
1218     return true;
1219   }
1220   case Intrinsic::objectsize: {
1221     ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1222     unsigned long long Res = CI->isZero() ? -1ULL : 0;
1223     Constant *ResCI = ConstantInt::get(II->getType(), Res);
1224     unsigned ResultReg = getRegForValue(ResCI);
1225     if (!ResultReg)
1226       return false;
1227     updateValueMap(II, ResultReg);
1228     return true;
1229   }
1230   case Intrinsic::expect: {
1231     unsigned ResultReg = getRegForValue(II->getArgOperand(0));
1232     if (!ResultReg)
1233       return false;
1234     updateValueMap(II, ResultReg);
1235     return true;
1236   }
1237   case Intrinsic::experimental_stackmap:
1238     return selectStackmap(II);
1239   case Intrinsic::experimental_patchpoint_void:
1240   case Intrinsic::experimental_patchpoint_i64:
1241     return selectPatchpoint(II);
1242   }
1243 
1244   return fastLowerIntrinsicCall(II);
1245 }
1246 
1247 bool FastISel::selectCast(const User *I, unsigned Opcode) {
1248   EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
1249   EVT DstVT = TLI.getValueType(DL, I->getType());
1250 
1251   if (SrcVT == MVT::Other || !SrcVT.isSimple() || DstVT == MVT::Other ||
1252       !DstVT.isSimple())
1253     // Unhandled type. Halt "fast" selection and bail.
1254     return false;
1255 
1256   // Check if the destination type is legal.
1257   if (!TLI.isTypeLegal(DstVT))
1258     return false;
1259 
1260   // Check if the source operand is legal.
1261   if (!TLI.isTypeLegal(SrcVT))
1262     return false;
1263 
1264   unsigned InputReg = getRegForValue(I->getOperand(0));
1265   if (!InputReg)
1266     // Unhandled operand.  Halt "fast" selection and bail.
1267     return false;
1268 
1269   bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
1270 
1271   unsigned ResultReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
1272                                   Opcode, InputReg, InputRegIsKill);
1273   if (!ResultReg)
1274     return false;
1275 
1276   updateValueMap(I, ResultReg);
1277   return true;
1278 }
1279 
1280 bool FastISel::selectBitCast(const User *I) {
1281   // If the bitcast doesn't change the type, just use the operand value.
1282   if (I->getType() == I->getOperand(0)->getType()) {
1283     unsigned Reg = getRegForValue(I->getOperand(0));
1284     if (!Reg)
1285       return false;
1286     updateValueMap(I, Reg);
1287     return true;
1288   }
1289 
1290   // Bitcasts of other values become reg-reg copies or BITCAST operators.
1291   EVT SrcEVT = TLI.getValueType(DL, I->getOperand(0)->getType());
1292   EVT DstEVT = TLI.getValueType(DL, I->getType());
1293   if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
1294       !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
1295     // Unhandled type. Halt "fast" selection and bail.
1296     return false;
1297 
1298   MVT SrcVT = SrcEVT.getSimpleVT();
1299   MVT DstVT = DstEVT.getSimpleVT();
1300   unsigned Op0 = getRegForValue(I->getOperand(0));
1301   if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
1302     return false;
1303   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
1304 
1305   // First, try to perform the bitcast by inserting a reg-reg copy.
1306   unsigned ResultReg = 0;
1307   if (SrcVT == DstVT) {
1308     const TargetRegisterClass *SrcClass = TLI.getRegClassFor(SrcVT);
1309     const TargetRegisterClass *DstClass = TLI.getRegClassFor(DstVT);
1310     // Don't attempt a cross-class copy. It will likely fail.
1311     if (SrcClass == DstClass) {
1312       ResultReg = createResultReg(DstClass);
1313       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1314               TII.get(TargetOpcode::COPY), ResultReg).addReg(Op0);
1315     }
1316   }
1317 
1318   // If the reg-reg copy failed, select a BITCAST opcode.
1319   if (!ResultReg)
1320     ResultReg = fastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
1321 
1322   if (!ResultReg)
1323     return false;
1324 
1325   updateValueMap(I, ResultReg);
1326   return true;
1327 }
1328 
1329 // Remove local value instructions starting from the instruction after
1330 // SavedLastLocalValue to the current function insert point.
1331 void FastISel::removeDeadLocalValueCode(MachineInstr *SavedLastLocalValue)
1332 {
1333   MachineInstr *CurLastLocalValue = getLastLocalValue();
1334   if (CurLastLocalValue != SavedLastLocalValue) {
1335     // Find the first local value instruction to be deleted.
1336     // This is the instruction after SavedLastLocalValue if it is non-NULL.
1337     // Otherwise it's the first instruction in the block.
1338     MachineBasicBlock::iterator FirstDeadInst(SavedLastLocalValue);
1339     if (SavedLastLocalValue)
1340       ++FirstDeadInst;
1341     else
1342       FirstDeadInst = FuncInfo.MBB->getFirstNonPHI();
1343     setLastLocalValue(SavedLastLocalValue);
1344     removeDeadCode(FirstDeadInst, FuncInfo.InsertPt);
1345   }
1346 }
1347 
1348 bool FastISel::selectInstruction(const Instruction *I) {
1349   MachineInstr *SavedLastLocalValue = getLastLocalValue();
1350   // Just before the terminator instruction, insert instructions to
1351   // feed PHI nodes in successor blocks.
1352   if (isa<TerminatorInst>(I))
1353     if (!handlePHINodesInSuccessorBlocks(I->getParent())) {
1354       // PHI node handling may have generated local value instructions,
1355       // even though it failed to handle all PHI nodes.
1356       // We remove these instructions because SelectionDAGISel will generate
1357       // them again.
1358       removeDeadLocalValueCode(SavedLastLocalValue);
1359       return false;
1360     }
1361 
1362   DbgLoc = I->getDebugLoc();
1363 
1364   SavedInsertPt = FuncInfo.InsertPt;
1365 
1366   if (const auto *Call = dyn_cast<CallInst>(I)) {
1367     const Function *F = Call->getCalledFunction();
1368     LibFunc::Func Func;
1369 
1370     // As a special case, don't handle calls to builtin library functions that
1371     // may be translated directly to target instructions.
1372     if (F && !F->hasLocalLinkage() && F->hasName() &&
1373         LibInfo->getLibFunc(F->getName(), Func) &&
1374         LibInfo->hasOptimizedCodeGen(Func))
1375       return false;
1376 
1377     // Don't handle Intrinsic::trap if a trap function is specified.
1378     if (F && F->getIntrinsicID() == Intrinsic::trap &&
1379         Call->hasFnAttr("trap-func-name"))
1380       return false;
1381   }
1382 
1383   // First, try doing target-independent selection.
1384   if (!SkipTargetIndependentISel) {
1385     if (selectOperator(I, I->getOpcode())) {
1386       ++NumFastIselSuccessIndependent;
1387       DbgLoc = DebugLoc();
1388       return true;
1389     }
1390     // Remove dead code.
1391     recomputeInsertPt();
1392     if (SavedInsertPt != FuncInfo.InsertPt)
1393       removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
1394     SavedInsertPt = FuncInfo.InsertPt;
1395   }
1396   // Next, try calling the target to attempt to handle the instruction.
1397   if (fastSelectInstruction(I)) {
1398     ++NumFastIselSuccessTarget;
1399     DbgLoc = DebugLoc();
1400     return true;
1401   }
1402   // Remove dead code.
1403   recomputeInsertPt();
1404   if (SavedInsertPt != FuncInfo.InsertPt)
1405     removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
1406 
1407   DbgLoc = DebugLoc();
1408   // Undo phi node updates, because they will be added again by SelectionDAG.
1409   if (isa<TerminatorInst>(I)) {
1410     // PHI node handling may have generated local value instructions.
1411     // We remove them because SelectionDAGISel will generate them again.
1412     removeDeadLocalValueCode(SavedLastLocalValue);
1413     FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
1414   }
1415   return false;
1416 }
1417 
1418 /// Emit an unconditional branch to the given block, unless it is the immediate
1419 /// (fall-through) successor, and update the CFG.
1420 void FastISel::fastEmitBranch(MachineBasicBlock *MSucc, DebugLoc DbgLoc) {
1421   if (FuncInfo.MBB->getBasicBlock()->size() > 1 &&
1422       FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
1423     // For more accurate line information if this is the only instruction
1424     // in the block then emit it, otherwise we have the unconditional
1425     // fall-through case, which needs no instructions.
1426   } else {
1427     // The unconditional branch case.
1428     TII.InsertBranch(*FuncInfo.MBB, MSucc, nullptr,
1429                      SmallVector<MachineOperand, 0>(), DbgLoc);
1430   }
1431   if (FuncInfo.BPI) {
1432     auto BranchProbability = FuncInfo.BPI->getEdgeProbability(
1433         FuncInfo.MBB->getBasicBlock(), MSucc->getBasicBlock());
1434     FuncInfo.MBB->addSuccessor(MSucc, BranchProbability);
1435   } else
1436     FuncInfo.MBB->addSuccessorWithoutProb(MSucc);
1437 }
1438 
1439 void FastISel::finishCondBranch(const BasicBlock *BranchBB,
1440                                 MachineBasicBlock *TrueMBB,
1441                                 MachineBasicBlock *FalseMBB) {
1442   // Add TrueMBB as successor unless it is equal to the FalseMBB: This can
1443   // happen in degenerate IR and MachineIR forbids to have a block twice in the
1444   // successor/predecessor lists.
1445   if (TrueMBB != FalseMBB) {
1446     if (FuncInfo.BPI) {
1447       auto BranchProbability =
1448           FuncInfo.BPI->getEdgeProbability(BranchBB, TrueMBB->getBasicBlock());
1449       FuncInfo.MBB->addSuccessor(TrueMBB, BranchProbability);
1450     } else
1451       FuncInfo.MBB->addSuccessorWithoutProb(TrueMBB);
1452   }
1453 
1454   fastEmitBranch(FalseMBB, DbgLoc);
1455 }
1456 
1457 /// Emit an FNeg operation.
1458 bool FastISel::selectFNeg(const User *I) {
1459   unsigned OpReg = getRegForValue(BinaryOperator::getFNegArgument(I));
1460   if (!OpReg)
1461     return false;
1462   bool OpRegIsKill = hasTrivialKill(I);
1463 
1464   // If the target has ISD::FNEG, use it.
1465   EVT VT = TLI.getValueType(DL, I->getType());
1466   unsigned ResultReg = fastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(), ISD::FNEG,
1467                                   OpReg, OpRegIsKill);
1468   if (ResultReg) {
1469     updateValueMap(I, ResultReg);
1470     return true;
1471   }
1472 
1473   // Bitcast the value to integer, twiddle the sign bit with xor,
1474   // and then bitcast it back to floating-point.
1475   if (VT.getSizeInBits() > 64)
1476     return false;
1477   EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
1478   if (!TLI.isTypeLegal(IntVT))
1479     return false;
1480 
1481   unsigned IntReg = fastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
1482                                ISD::BITCAST, OpReg, OpRegIsKill);
1483   if (!IntReg)
1484     return false;
1485 
1486   unsigned IntResultReg = fastEmit_ri_(
1487       IntVT.getSimpleVT(), ISD::XOR, IntReg, /*IsKill=*/true,
1488       UINT64_C(1) << (VT.getSizeInBits() - 1), IntVT.getSimpleVT());
1489   if (!IntResultReg)
1490     return false;
1491 
1492   ResultReg = fastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(), ISD::BITCAST,
1493                          IntResultReg, /*IsKill=*/true);
1494   if (!ResultReg)
1495     return false;
1496 
1497   updateValueMap(I, ResultReg);
1498   return true;
1499 }
1500 
1501 bool FastISel::selectExtractValue(const User *U) {
1502   const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
1503   if (!EVI)
1504     return false;
1505 
1506   // Make sure we only try to handle extracts with a legal result.  But also
1507   // allow i1 because it's easy.
1508   EVT RealVT = TLI.getValueType(DL, EVI->getType(), /*AllowUnknown=*/true);
1509   if (!RealVT.isSimple())
1510     return false;
1511   MVT VT = RealVT.getSimpleVT();
1512   if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
1513     return false;
1514 
1515   const Value *Op0 = EVI->getOperand(0);
1516   Type *AggTy = Op0->getType();
1517 
1518   // Get the base result register.
1519   unsigned ResultReg;
1520   DenseMap<const Value *, unsigned>::iterator I = FuncInfo.ValueMap.find(Op0);
1521   if (I != FuncInfo.ValueMap.end())
1522     ResultReg = I->second;
1523   else if (isa<Instruction>(Op0))
1524     ResultReg = FuncInfo.InitializeRegForValue(Op0);
1525   else
1526     return false; // fast-isel can't handle aggregate constants at the moment
1527 
1528   // Get the actual result register, which is an offset from the base register.
1529   unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
1530 
1531   SmallVector<EVT, 4> AggValueVTs;
1532   ComputeValueVTs(TLI, DL, AggTy, AggValueVTs);
1533 
1534   for (unsigned i = 0; i < VTIndex; i++)
1535     ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
1536 
1537   updateValueMap(EVI, ResultReg);
1538   return true;
1539 }
1540 
1541 bool FastISel::selectOperator(const User *I, unsigned Opcode) {
1542   switch (Opcode) {
1543   case Instruction::Add:
1544     return selectBinaryOp(I, ISD::ADD);
1545   case Instruction::FAdd:
1546     return selectBinaryOp(I, ISD::FADD);
1547   case Instruction::Sub:
1548     return selectBinaryOp(I, ISD::SUB);
1549   case Instruction::FSub:
1550     // FNeg is currently represented in LLVM IR as a special case of FSub.
1551     if (BinaryOperator::isFNeg(I))
1552       return selectFNeg(I);
1553     return selectBinaryOp(I, ISD::FSUB);
1554   case Instruction::Mul:
1555     return selectBinaryOp(I, ISD::MUL);
1556   case Instruction::FMul:
1557     return selectBinaryOp(I, ISD::FMUL);
1558   case Instruction::SDiv:
1559     return selectBinaryOp(I, ISD::SDIV);
1560   case Instruction::UDiv:
1561     return selectBinaryOp(I, ISD::UDIV);
1562   case Instruction::FDiv:
1563     return selectBinaryOp(I, ISD::FDIV);
1564   case Instruction::SRem:
1565     return selectBinaryOp(I, ISD::SREM);
1566   case Instruction::URem:
1567     return selectBinaryOp(I, ISD::UREM);
1568   case Instruction::FRem:
1569     return selectBinaryOp(I, ISD::FREM);
1570   case Instruction::Shl:
1571     return selectBinaryOp(I, ISD::SHL);
1572   case Instruction::LShr:
1573     return selectBinaryOp(I, ISD::SRL);
1574   case Instruction::AShr:
1575     return selectBinaryOp(I, ISD::SRA);
1576   case Instruction::And:
1577     return selectBinaryOp(I, ISD::AND);
1578   case Instruction::Or:
1579     return selectBinaryOp(I, ISD::OR);
1580   case Instruction::Xor:
1581     return selectBinaryOp(I, ISD::XOR);
1582 
1583   case Instruction::GetElementPtr:
1584     return selectGetElementPtr(I);
1585 
1586   case Instruction::Br: {
1587     const BranchInst *BI = cast<BranchInst>(I);
1588 
1589     if (BI->isUnconditional()) {
1590       const BasicBlock *LLVMSucc = BI->getSuccessor(0);
1591       MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
1592       fastEmitBranch(MSucc, BI->getDebugLoc());
1593       return true;
1594     }
1595 
1596     // Conditional branches are not handed yet.
1597     // Halt "fast" selection and bail.
1598     return false;
1599   }
1600 
1601   case Instruction::Unreachable:
1602     if (TM.Options.TrapUnreachable)
1603       return fastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0;
1604     else
1605       return true;
1606 
1607   case Instruction::Alloca:
1608     // FunctionLowering has the static-sized case covered.
1609     if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
1610       return true;
1611 
1612     // Dynamic-sized alloca is not handled yet.
1613     return false;
1614 
1615   case Instruction::Call:
1616     return selectCall(I);
1617 
1618   case Instruction::BitCast:
1619     return selectBitCast(I);
1620 
1621   case Instruction::FPToSI:
1622     return selectCast(I, ISD::FP_TO_SINT);
1623   case Instruction::ZExt:
1624     return selectCast(I, ISD::ZERO_EXTEND);
1625   case Instruction::SExt:
1626     return selectCast(I, ISD::SIGN_EXTEND);
1627   case Instruction::Trunc:
1628     return selectCast(I, ISD::TRUNCATE);
1629   case Instruction::SIToFP:
1630     return selectCast(I, ISD::SINT_TO_FP);
1631 
1632   case Instruction::IntToPtr: // Deliberate fall-through.
1633   case Instruction::PtrToInt: {
1634     EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
1635     EVT DstVT = TLI.getValueType(DL, I->getType());
1636     if (DstVT.bitsGT(SrcVT))
1637       return selectCast(I, ISD::ZERO_EXTEND);
1638     if (DstVT.bitsLT(SrcVT))
1639       return selectCast(I, ISD::TRUNCATE);
1640     unsigned Reg = getRegForValue(I->getOperand(0));
1641     if (!Reg)
1642       return false;
1643     updateValueMap(I, Reg);
1644     return true;
1645   }
1646 
1647   case Instruction::ExtractValue:
1648     return selectExtractValue(I);
1649 
1650   case Instruction::PHI:
1651     llvm_unreachable("FastISel shouldn't visit PHI nodes!");
1652 
1653   default:
1654     // Unhandled instruction. Halt "fast" selection and bail.
1655     return false;
1656   }
1657 }
1658 
1659 FastISel::FastISel(FunctionLoweringInfo &FuncInfo,
1660                    const TargetLibraryInfo *LibInfo,
1661                    bool SkipTargetIndependentISel)
1662     : FuncInfo(FuncInfo), MF(FuncInfo.MF), MRI(FuncInfo.MF->getRegInfo()),
1663       MFI(*FuncInfo.MF->getFrameInfo()), MCP(*FuncInfo.MF->getConstantPool()),
1664       TM(FuncInfo.MF->getTarget()), DL(MF->getDataLayout()),
1665       TII(*MF->getSubtarget().getInstrInfo()),
1666       TLI(*MF->getSubtarget().getTargetLowering()),
1667       TRI(*MF->getSubtarget().getRegisterInfo()), LibInfo(LibInfo),
1668       SkipTargetIndependentISel(SkipTargetIndependentISel) {}
1669 
1670 FastISel::~FastISel() {}
1671 
1672 bool FastISel::fastLowerArguments() { return false; }
1673 
1674 bool FastISel::fastLowerCall(CallLoweringInfo & /*CLI*/) { return false; }
1675 
1676 bool FastISel::fastLowerIntrinsicCall(const IntrinsicInst * /*II*/) {
1677   return false;
1678 }
1679 
1680 unsigned FastISel::fastEmit_(MVT, MVT, unsigned) { return 0; }
1681 
1682 unsigned FastISel::fastEmit_r(MVT, MVT, unsigned, unsigned /*Op0*/,
1683                               bool /*Op0IsKill*/) {
1684   return 0;
1685 }
1686 
1687 unsigned FastISel::fastEmit_rr(MVT, MVT, unsigned, unsigned /*Op0*/,
1688                                bool /*Op0IsKill*/, unsigned /*Op1*/,
1689                                bool /*Op1IsKill*/) {
1690   return 0;
1691 }
1692 
1693 unsigned FastISel::fastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
1694   return 0;
1695 }
1696 
1697 unsigned FastISel::fastEmit_f(MVT, MVT, unsigned,
1698                               const ConstantFP * /*FPImm*/) {
1699   return 0;
1700 }
1701 
1702 unsigned FastISel::fastEmit_ri(MVT, MVT, unsigned, unsigned /*Op0*/,
1703                                bool /*Op0IsKill*/, uint64_t /*Imm*/) {
1704   return 0;
1705 }
1706 
1707 unsigned FastISel::fastEmit_rf(MVT, MVT, unsigned, unsigned /*Op0*/,
1708                                bool /*Op0IsKill*/,
1709                                const ConstantFP * /*FPImm*/) {
1710   return 0;
1711 }
1712 
1713 unsigned FastISel::fastEmit_rri(MVT, MVT, unsigned, unsigned /*Op0*/,
1714                                 bool /*Op0IsKill*/, unsigned /*Op1*/,
1715                                 bool /*Op1IsKill*/, uint64_t /*Imm*/) {
1716   return 0;
1717 }
1718 
1719 /// This method is a wrapper of fastEmit_ri. It first tries to emit an
1720 /// instruction with an immediate operand using fastEmit_ri.
1721 /// If that fails, it materializes the immediate into a register and try
1722 /// fastEmit_rr instead.
1723 unsigned FastISel::fastEmit_ri_(MVT VT, unsigned Opcode, unsigned Op0,
1724                                 bool Op0IsKill, uint64_t Imm, MVT ImmType) {
1725   // If this is a multiply by a power of two, emit this as a shift left.
1726   if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
1727     Opcode = ISD::SHL;
1728     Imm = Log2_64(Imm);
1729   } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
1730     // div x, 8 -> srl x, 3
1731     Opcode = ISD::SRL;
1732     Imm = Log2_64(Imm);
1733   }
1734 
1735   // Horrible hack (to be removed), check to make sure shift amounts are
1736   // in-range.
1737   if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
1738       Imm >= VT.getSizeInBits())
1739     return 0;
1740 
1741   // First check if immediate type is legal. If not, we can't use the ri form.
1742   unsigned ResultReg = fastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
1743   if (ResultReg)
1744     return ResultReg;
1745   unsigned MaterialReg = fastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
1746   bool IsImmKill = true;
1747   if (!MaterialReg) {
1748     // This is a bit ugly/slow, but failing here means falling out of
1749     // fast-isel, which would be very slow.
1750     IntegerType *ITy =
1751         IntegerType::get(FuncInfo.Fn->getContext(), VT.getSizeInBits());
1752     MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
1753     if (!MaterialReg)
1754       return 0;
1755     // FIXME: If the materialized register here has no uses yet then this
1756     // will be the first use and we should be able to mark it as killed.
1757     // However, the local value area for materialising constant expressions
1758     // grows down, not up, which means that any constant expressions we generate
1759     // later which also use 'Imm' could be after this instruction and therefore
1760     // after this kill.
1761     IsImmKill = false;
1762   }
1763   return fastEmit_rr(VT, VT, Opcode, Op0, Op0IsKill, MaterialReg, IsImmKill);
1764 }
1765 
1766 unsigned FastISel::createResultReg(const TargetRegisterClass *RC) {
1767   return MRI.createVirtualRegister(RC);
1768 }
1769 
1770 unsigned FastISel::constrainOperandRegClass(const MCInstrDesc &II, unsigned Op,
1771                                             unsigned OpNum) {
1772   if (TargetRegisterInfo::isVirtualRegister(Op)) {
1773     const TargetRegisterClass *RegClass =
1774         TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF);
1775     if (!MRI.constrainRegClass(Op, RegClass)) {
1776       // If it's not legal to COPY between the register classes, something
1777       // has gone very wrong before we got here.
1778       unsigned NewOp = createResultReg(RegClass);
1779       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1780               TII.get(TargetOpcode::COPY), NewOp).addReg(Op);
1781       return NewOp;
1782     }
1783   }
1784   return Op;
1785 }
1786 
1787 unsigned FastISel::fastEmitInst_(unsigned MachineInstOpcode,
1788                                  const TargetRegisterClass *RC) {
1789   unsigned ResultReg = createResultReg(RC);
1790   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1791 
1792   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg);
1793   return ResultReg;
1794 }
1795 
1796 unsigned FastISel::fastEmitInst_r(unsigned MachineInstOpcode,
1797                                   const TargetRegisterClass *RC, unsigned Op0,
1798                                   bool Op0IsKill) {
1799   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1800 
1801   unsigned ResultReg = createResultReg(RC);
1802   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
1803 
1804   if (II.getNumDefs() >= 1)
1805     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1806         .addReg(Op0, getKillRegState(Op0IsKill));
1807   else {
1808     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1809         .addReg(Op0, getKillRegState(Op0IsKill));
1810     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1811             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1812   }
1813 
1814   return ResultReg;
1815 }
1816 
1817 unsigned FastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
1818                                    const TargetRegisterClass *RC, unsigned Op0,
1819                                    bool Op0IsKill, unsigned Op1,
1820                                    bool Op1IsKill) {
1821   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1822 
1823   unsigned ResultReg = createResultReg(RC);
1824   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
1825   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
1826 
1827   if (II.getNumDefs() >= 1)
1828     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1829         .addReg(Op0, getKillRegState(Op0IsKill))
1830         .addReg(Op1, getKillRegState(Op1IsKill));
1831   else {
1832     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1833         .addReg(Op0, getKillRegState(Op0IsKill))
1834         .addReg(Op1, getKillRegState(Op1IsKill));
1835     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1836             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1837   }
1838   return ResultReg;
1839 }
1840 
1841 unsigned FastISel::fastEmitInst_rrr(unsigned MachineInstOpcode,
1842                                     const TargetRegisterClass *RC, unsigned Op0,
1843                                     bool Op0IsKill, unsigned Op1,
1844                                     bool Op1IsKill, unsigned Op2,
1845                                     bool Op2IsKill) {
1846   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1847 
1848   unsigned ResultReg = createResultReg(RC);
1849   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
1850   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
1851   Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
1852 
1853   if (II.getNumDefs() >= 1)
1854     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1855         .addReg(Op0, getKillRegState(Op0IsKill))
1856         .addReg(Op1, getKillRegState(Op1IsKill))
1857         .addReg(Op2, getKillRegState(Op2IsKill));
1858   else {
1859     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1860         .addReg(Op0, getKillRegState(Op0IsKill))
1861         .addReg(Op1, getKillRegState(Op1IsKill))
1862         .addReg(Op2, getKillRegState(Op2IsKill));
1863     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1864             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1865   }
1866   return ResultReg;
1867 }
1868 
1869 unsigned FastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
1870                                    const TargetRegisterClass *RC, unsigned Op0,
1871                                    bool Op0IsKill, uint64_t Imm) {
1872   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1873 
1874   unsigned ResultReg = createResultReg(RC);
1875   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
1876 
1877   if (II.getNumDefs() >= 1)
1878     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1879         .addReg(Op0, getKillRegState(Op0IsKill))
1880         .addImm(Imm);
1881   else {
1882     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1883         .addReg(Op0, getKillRegState(Op0IsKill))
1884         .addImm(Imm);
1885     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1886             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1887   }
1888   return ResultReg;
1889 }
1890 
1891 unsigned FastISel::fastEmitInst_rii(unsigned MachineInstOpcode,
1892                                     const TargetRegisterClass *RC, unsigned Op0,
1893                                     bool Op0IsKill, uint64_t Imm1,
1894                                     uint64_t Imm2) {
1895   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1896 
1897   unsigned ResultReg = createResultReg(RC);
1898   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
1899 
1900   if (II.getNumDefs() >= 1)
1901     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1902         .addReg(Op0, getKillRegState(Op0IsKill))
1903         .addImm(Imm1)
1904         .addImm(Imm2);
1905   else {
1906     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1907         .addReg(Op0, getKillRegState(Op0IsKill))
1908         .addImm(Imm1)
1909         .addImm(Imm2);
1910     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1911             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1912   }
1913   return ResultReg;
1914 }
1915 
1916 unsigned FastISel::fastEmitInst_f(unsigned MachineInstOpcode,
1917                                   const TargetRegisterClass *RC,
1918                                   const ConstantFP *FPImm) {
1919   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1920 
1921   unsigned ResultReg = createResultReg(RC);
1922 
1923   if (II.getNumDefs() >= 1)
1924     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1925         .addFPImm(FPImm);
1926   else {
1927     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1928         .addFPImm(FPImm);
1929     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1930             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1931   }
1932   return ResultReg;
1933 }
1934 
1935 unsigned FastISel::fastEmitInst_rri(unsigned MachineInstOpcode,
1936                                     const TargetRegisterClass *RC, unsigned Op0,
1937                                     bool Op0IsKill, unsigned Op1,
1938                                     bool Op1IsKill, uint64_t Imm) {
1939   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1940 
1941   unsigned ResultReg = createResultReg(RC);
1942   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
1943   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
1944 
1945   if (II.getNumDefs() >= 1)
1946     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1947         .addReg(Op0, getKillRegState(Op0IsKill))
1948         .addReg(Op1, getKillRegState(Op1IsKill))
1949         .addImm(Imm);
1950   else {
1951     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1952         .addReg(Op0, getKillRegState(Op0IsKill))
1953         .addReg(Op1, getKillRegState(Op1IsKill))
1954         .addImm(Imm);
1955     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1956             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1957   }
1958   return ResultReg;
1959 }
1960 
1961 unsigned FastISel::fastEmitInst_i(unsigned MachineInstOpcode,
1962                                   const TargetRegisterClass *RC, uint64_t Imm) {
1963   unsigned ResultReg = createResultReg(RC);
1964   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1965 
1966   if (II.getNumDefs() >= 1)
1967     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1968         .addImm(Imm);
1969   else {
1970     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm);
1971     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1972             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1973   }
1974   return ResultReg;
1975 }
1976 
1977 unsigned FastISel::fastEmitInst_extractsubreg(MVT RetVT, unsigned Op0,
1978                                               bool Op0IsKill, uint32_t Idx) {
1979   unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
1980   assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
1981          "Cannot yet extract from physregs");
1982   const TargetRegisterClass *RC = MRI.getRegClass(Op0);
1983   MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
1984   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1985           ResultReg).addReg(Op0, getKillRegState(Op0IsKill), Idx);
1986   return ResultReg;
1987 }
1988 
1989 /// Emit MachineInstrs to compute the value of Op with all but the least
1990 /// significant bit set to zero.
1991 unsigned FastISel::fastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
1992   return fastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
1993 }
1994 
1995 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
1996 /// Emit code to ensure constants are copied into registers when needed.
1997 /// Remember the virtual registers that need to be added to the Machine PHI
1998 /// nodes as input.  We cannot just directly add them, because expansion
1999 /// might result in multiple MBB's for one BB.  As such, the start of the
2000 /// BB might correspond to a different MBB than the end.
2001 bool FastISel::handlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
2002   const TerminatorInst *TI = LLVMBB->getTerminator();
2003 
2004   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
2005   FuncInfo.OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
2006 
2007   // Check successor nodes' PHI nodes that expect a constant to be available
2008   // from this block.
2009   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2010     const BasicBlock *SuccBB = TI->getSuccessor(succ);
2011     if (!isa<PHINode>(SuccBB->begin()))
2012       continue;
2013     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
2014 
2015     // If this terminator has multiple identical successors (common for
2016     // switches), only handle each succ once.
2017     if (!SuccsHandled.insert(SuccMBB).second)
2018       continue;
2019 
2020     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
2021 
2022     // At this point we know that there is a 1-1 correspondence between LLVM PHI
2023     // nodes and Machine PHI nodes, but the incoming operands have not been
2024     // emitted yet.
2025     for (BasicBlock::const_iterator I = SuccBB->begin();
2026          const auto *PN = dyn_cast<PHINode>(I); ++I) {
2027 
2028       // Ignore dead phi's.
2029       if (PN->use_empty())
2030         continue;
2031 
2032       // Only handle legal types. Two interesting things to note here. First,
2033       // by bailing out early, we may leave behind some dead instructions,
2034       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
2035       // own moves. Second, this check is necessary because FastISel doesn't
2036       // use CreateRegs to create registers, so it always creates
2037       // exactly one register for each non-void instruction.
2038       EVT VT = TLI.getValueType(DL, PN->getType(), /*AllowUnknown=*/true);
2039       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
2040         // Handle integer promotions, though, because they're common and easy.
2041         if (!(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)) {
2042           FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
2043           return false;
2044         }
2045       }
2046 
2047       const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2048 
2049       // Set the DebugLoc for the copy. Prefer the location of the operand
2050       // if there is one; use the location of the PHI otherwise.
2051       DbgLoc = PN->getDebugLoc();
2052       if (const auto *Inst = dyn_cast<Instruction>(PHIOp))
2053         DbgLoc = Inst->getDebugLoc();
2054 
2055       unsigned Reg = getRegForValue(PHIOp);
2056       if (!Reg) {
2057         FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
2058         return false;
2059       }
2060       FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
2061       DbgLoc = DebugLoc();
2062     }
2063   }
2064 
2065   return true;
2066 }
2067 
2068 bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) {
2069   assert(LI->hasOneUse() &&
2070          "tryToFoldLoad expected a LoadInst with a single use");
2071   // We know that the load has a single use, but don't know what it is.  If it
2072   // isn't one of the folded instructions, then we can't succeed here.  Handle
2073   // this by scanning the single-use users of the load until we get to FoldInst.
2074   unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs.
2075 
2076   const Instruction *TheUser = LI->user_back();
2077   while (TheUser != FoldInst && // Scan up until we find FoldInst.
2078          // Stay in the right block.
2079          TheUser->getParent() == FoldInst->getParent() &&
2080          --MaxUsers) { // Don't scan too far.
2081     // If there are multiple or no uses of this instruction, then bail out.
2082     if (!TheUser->hasOneUse())
2083       return false;
2084 
2085     TheUser = TheUser->user_back();
2086   }
2087 
2088   // If we didn't find the fold instruction, then we failed to collapse the
2089   // sequence.
2090   if (TheUser != FoldInst)
2091     return false;
2092 
2093   // Don't try to fold volatile loads.  Target has to deal with alignment
2094   // constraints.
2095   if (LI->isVolatile())
2096     return false;
2097 
2098   // Figure out which vreg this is going into.  If there is no assigned vreg yet
2099   // then there actually was no reference to it.  Perhaps the load is referenced
2100   // by a dead instruction.
2101   unsigned LoadReg = getRegForValue(LI);
2102   if (!LoadReg)
2103     return false;
2104 
2105   // We can't fold if this vreg has no uses or more than one use.  Multiple uses
2106   // may mean that the instruction got lowered to multiple MIs, or the use of
2107   // the loaded value ended up being multiple operands of the result.
2108   if (!MRI.hasOneUse(LoadReg))
2109     return false;
2110 
2111   MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg);
2112   MachineInstr *User = RI->getParent();
2113 
2114   // Set the insertion point properly.  Folding the load can cause generation of
2115   // other random instructions (like sign extends) for addressing modes; make
2116   // sure they get inserted in a logical place before the new instruction.
2117   FuncInfo.InsertPt = User;
2118   FuncInfo.MBB = User->getParent();
2119 
2120   // Ask the target to try folding the load.
2121   return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI);
2122 }
2123 
2124 bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) {
2125   // Must be an add.
2126   if (!isa<AddOperator>(Add))
2127     return false;
2128   // Type size needs to match.
2129   if (DL.getTypeSizeInBits(GEP->getType()) !=
2130       DL.getTypeSizeInBits(Add->getType()))
2131     return false;
2132   // Must be in the same basic block.
2133   if (isa<Instruction>(Add) &&
2134       FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB)
2135     return false;
2136   // Must have a constant operand.
2137   return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1));
2138 }
2139 
2140 MachineMemOperand *
2141 FastISel::createMachineMemOperandFor(const Instruction *I) const {
2142   const Value *Ptr;
2143   Type *ValTy;
2144   unsigned Alignment;
2145   unsigned Flags;
2146   bool IsVolatile;
2147 
2148   if (const auto *LI = dyn_cast<LoadInst>(I)) {
2149     Alignment = LI->getAlignment();
2150     IsVolatile = LI->isVolatile();
2151     Flags = MachineMemOperand::MOLoad;
2152     Ptr = LI->getPointerOperand();
2153     ValTy = LI->getType();
2154   } else if (const auto *SI = dyn_cast<StoreInst>(I)) {
2155     Alignment = SI->getAlignment();
2156     IsVolatile = SI->isVolatile();
2157     Flags = MachineMemOperand::MOStore;
2158     Ptr = SI->getPointerOperand();
2159     ValTy = SI->getValueOperand()->getType();
2160   } else
2161     return nullptr;
2162 
2163   bool IsNonTemporal = I->getMetadata(LLVMContext::MD_nontemporal) != nullptr;
2164   bool IsInvariant = I->getMetadata(LLVMContext::MD_invariant_load) != nullptr;
2165   const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range);
2166 
2167   AAMDNodes AAInfo;
2168   I->getAAMetadata(AAInfo);
2169 
2170   if (Alignment == 0) // Ensure that codegen never sees alignment 0.
2171     Alignment = DL.getABITypeAlignment(ValTy);
2172 
2173   unsigned Size = DL.getTypeStoreSize(ValTy);
2174 
2175   if (IsVolatile)
2176     Flags |= MachineMemOperand::MOVolatile;
2177   if (IsNonTemporal)
2178     Flags |= MachineMemOperand::MONonTemporal;
2179   if (IsInvariant)
2180     Flags |= MachineMemOperand::MOInvariant;
2181 
2182   return FuncInfo.MF->getMachineMemOperand(MachinePointerInfo(Ptr), Flags, Size,
2183                                            Alignment, AAInfo, Ranges);
2184 }
2185 
2186 CmpInst::Predicate FastISel::optimizeCmpPredicate(const CmpInst *CI) const {
2187   // If both operands are the same, then try to optimize or fold the cmp.
2188   CmpInst::Predicate Predicate = CI->getPredicate();
2189   if (CI->getOperand(0) != CI->getOperand(1))
2190     return Predicate;
2191 
2192   switch (Predicate) {
2193   default: llvm_unreachable("Invalid predicate!");
2194   case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
2195   case CmpInst::FCMP_OEQ:   Predicate = CmpInst::FCMP_ORD;   break;
2196   case CmpInst::FCMP_OGT:   Predicate = CmpInst::FCMP_FALSE; break;
2197   case CmpInst::FCMP_OGE:   Predicate = CmpInst::FCMP_ORD;   break;
2198   case CmpInst::FCMP_OLT:   Predicate = CmpInst::FCMP_FALSE; break;
2199   case CmpInst::FCMP_OLE:   Predicate = CmpInst::FCMP_ORD;   break;
2200   case CmpInst::FCMP_ONE:   Predicate = CmpInst::FCMP_FALSE; break;
2201   case CmpInst::FCMP_ORD:   Predicate = CmpInst::FCMP_ORD;   break;
2202   case CmpInst::FCMP_UNO:   Predicate = CmpInst::FCMP_UNO;   break;
2203   case CmpInst::FCMP_UEQ:   Predicate = CmpInst::FCMP_TRUE;  break;
2204   case CmpInst::FCMP_UGT:   Predicate = CmpInst::FCMP_UNO;   break;
2205   case CmpInst::FCMP_UGE:   Predicate = CmpInst::FCMP_TRUE;  break;
2206   case CmpInst::FCMP_ULT:   Predicate = CmpInst::FCMP_UNO;   break;
2207   case CmpInst::FCMP_ULE:   Predicate = CmpInst::FCMP_TRUE;  break;
2208   case CmpInst::FCMP_UNE:   Predicate = CmpInst::FCMP_UNO;   break;
2209   case CmpInst::FCMP_TRUE:  Predicate = CmpInst::FCMP_TRUE;  break;
2210 
2211   case CmpInst::ICMP_EQ:    Predicate = CmpInst::FCMP_TRUE;  break;
2212   case CmpInst::ICMP_NE:    Predicate = CmpInst::FCMP_FALSE; break;
2213   case CmpInst::ICMP_UGT:   Predicate = CmpInst::FCMP_FALSE; break;
2214   case CmpInst::ICMP_UGE:   Predicate = CmpInst::FCMP_TRUE;  break;
2215   case CmpInst::ICMP_ULT:   Predicate = CmpInst::FCMP_FALSE; break;
2216   case CmpInst::ICMP_ULE:   Predicate = CmpInst::FCMP_TRUE;  break;
2217   case CmpInst::ICMP_SGT:   Predicate = CmpInst::FCMP_FALSE; break;
2218   case CmpInst::ICMP_SGE:   Predicate = CmpInst::FCMP_TRUE;  break;
2219   case CmpInst::ICMP_SLT:   Predicate = CmpInst::FCMP_FALSE; break;
2220   case CmpInst::ICMP_SLE:   Predicate = CmpInst::FCMP_TRUE;  break;
2221   }
2222 
2223   return Predicate;
2224 }
2225