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