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