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