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