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     return true;
1256   case Intrinsic::dbg_declare: {
1257     const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
1258     assert(DI->getVariable() && "Missing variable");
1259     if (!FuncInfo.MF->getMMI().hasDebugInfo()) {
1260       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI
1261                         << " (!hasDebugInfo)\n");
1262       return true;
1263     }
1264 
1265     const Value *Address = DI->getAddress();
1266     if (!Address || isa<UndefValue>(Address)) {
1267       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI
1268                         << " (bad/undef address)\n");
1269       return true;
1270     }
1271 
1272     // Byval arguments with frame indices were already handled after argument
1273     // lowering and before isel.
1274     const auto *Arg =
1275         dyn_cast<Argument>(Address->stripInBoundsConstantOffsets());
1276     if (Arg && FuncInfo.getArgumentFrameIndex(Arg) != INT_MAX)
1277       return true;
1278 
1279     Optional<MachineOperand> Op;
1280     if (Register Reg = lookUpRegForValue(Address))
1281       Op = MachineOperand::CreateReg(Reg, false);
1282 
1283     // If we have a VLA that has a "use" in a metadata node that's then used
1284     // here but it has no other uses, then we have a problem. E.g.,
1285     //
1286     //   int foo (const int *x) {
1287     //     char a[*x];
1288     //     return 0;
1289     //   }
1290     //
1291     // If we assign 'a' a vreg and fast isel later on has to use the selection
1292     // DAG isel, it will want to copy the value to the vreg. However, there are
1293     // no uses, which goes counter to what selection DAG isel expects.
1294     if (!Op && !Address->use_empty() && isa<Instruction>(Address) &&
1295         (!isa<AllocaInst>(Address) ||
1296          !FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
1297       Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address),
1298                                      false);
1299 
1300     if (Op) {
1301       assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
1302              "Expected inlined-at fields to agree");
1303       // A dbg.declare describes the address of a source variable, so lower it
1304       // into an indirect DBG_VALUE.
1305       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1306               TII.get(TargetOpcode::DBG_VALUE), /*IsIndirect*/ true,
1307               *Op, DI->getVariable(), DI->getExpression());
1308     } else {
1309       // We can't yet handle anything else here because it would require
1310       // generating code, thus altering codegen because of debug info.
1311       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI
1312                         << " (no materialized reg for address)\n");
1313     }
1314     return true;
1315   }
1316   case Intrinsic::dbg_value: {
1317     // This form of DBG_VALUE is target-independent.
1318     const DbgValueInst *DI = cast<DbgValueInst>(II);
1319     const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
1320     const Value *V = DI->getValue();
1321     assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
1322            "Expected inlined-at fields to agree");
1323     if (!V || isa<UndefValue>(V)) {
1324       // Currently the optimizer can produce this; insert an undef to
1325       // help debugging.
1326       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, false, 0U,
1327               DI->getVariable(), DI->getExpression());
1328     } else if (const auto *CI = dyn_cast<ConstantInt>(V)) {
1329       if (CI->getBitWidth() > 64)
1330         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1331             .addCImm(CI)
1332             .addImm(0U)
1333             .addMetadata(DI->getVariable())
1334             .addMetadata(DI->getExpression());
1335       else
1336         BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1337             .addImm(CI->getZExtValue())
1338             .addImm(0U)
1339             .addMetadata(DI->getVariable())
1340             .addMetadata(DI->getExpression());
1341     } else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
1342       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1343           .addFPImm(CF)
1344           .addImm(0U)
1345           .addMetadata(DI->getVariable())
1346           .addMetadata(DI->getExpression());
1347     } else if (Register Reg = lookUpRegForValue(V)) {
1348       // FIXME: This does not handle register-indirect values at offset 0.
1349       bool IsIndirect = false;
1350       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, IsIndirect, Reg,
1351               DI->getVariable(), DI->getExpression());
1352     } else {
1353       // We don't know how to handle other cases, so we drop.
1354       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1355     }
1356     return true;
1357   }
1358   case Intrinsic::dbg_label: {
1359     const DbgLabelInst *DI = cast<DbgLabelInst>(II);
1360     assert(DI->getLabel() && "Missing label");
1361     if (!FuncInfo.MF->getMMI().hasDebugInfo()) {
1362       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1363       return true;
1364     }
1365 
1366     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1367             TII.get(TargetOpcode::DBG_LABEL)).addMetadata(DI->getLabel());
1368     return true;
1369   }
1370   case Intrinsic::objectsize:
1371     llvm_unreachable("llvm.objectsize.* should have been lowered already");
1372 
1373   case Intrinsic::is_constant:
1374     llvm_unreachable("llvm.is.constant.* should have been lowered already");
1375 
1376   case Intrinsic::launder_invariant_group:
1377   case Intrinsic::strip_invariant_group:
1378   case Intrinsic::expect: {
1379     Register ResultReg = getRegForValue(II->getArgOperand(0));
1380     if (!ResultReg)
1381       return false;
1382     updateValueMap(II, ResultReg);
1383     return true;
1384   }
1385   case Intrinsic::experimental_stackmap:
1386     return selectStackmap(II);
1387   case Intrinsic::experimental_patchpoint_void:
1388   case Intrinsic::experimental_patchpoint_i64:
1389     return selectPatchpoint(II);
1390 
1391   case Intrinsic::xray_customevent:
1392     return selectXRayCustomEvent(II);
1393   case Intrinsic::xray_typedevent:
1394     return selectXRayTypedEvent(II);
1395   }
1396 
1397   return fastLowerIntrinsicCall(II);
1398 }
1399 
1400 bool FastISel::selectCast(const User *I, unsigned Opcode) {
1401   EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
1402   EVT DstVT = TLI.getValueType(DL, I->getType());
1403 
1404   if (SrcVT == MVT::Other || !SrcVT.isSimple() || DstVT == MVT::Other ||
1405       !DstVT.isSimple())
1406     // Unhandled type. Halt "fast" selection and bail.
1407     return false;
1408 
1409   // Check if the destination type is legal.
1410   if (!TLI.isTypeLegal(DstVT))
1411     return false;
1412 
1413   // Check if the source operand is legal.
1414   if (!TLI.isTypeLegal(SrcVT))
1415     return false;
1416 
1417   Register InputReg = getRegForValue(I->getOperand(0));
1418   if (!InputReg)
1419     // Unhandled operand.  Halt "fast" selection and bail.
1420     return false;
1421 
1422   bool InputRegIsKill = hasTrivialKill(I->getOperand(0));
1423 
1424   Register ResultReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
1425                                   Opcode, InputReg, InputRegIsKill);
1426   if (!ResultReg)
1427     return false;
1428 
1429   updateValueMap(I, ResultReg);
1430   return true;
1431 }
1432 
1433 bool FastISel::selectBitCast(const User *I) {
1434   // If the bitcast doesn't change the type, just use the operand value.
1435   if (I->getType() == I->getOperand(0)->getType()) {
1436     Register Reg = getRegForValue(I->getOperand(0));
1437     if (!Reg)
1438       return false;
1439     updateValueMap(I, Reg);
1440     return true;
1441   }
1442 
1443   // Bitcasts of other values become reg-reg copies or BITCAST operators.
1444   EVT SrcEVT = TLI.getValueType(DL, I->getOperand(0)->getType());
1445   EVT DstEVT = TLI.getValueType(DL, I->getType());
1446   if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
1447       !TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
1448     // Unhandled type. Halt "fast" selection and bail.
1449     return false;
1450 
1451   MVT SrcVT = SrcEVT.getSimpleVT();
1452   MVT DstVT = DstEVT.getSimpleVT();
1453   Register Op0 = getRegForValue(I->getOperand(0));
1454   if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
1455     return false;
1456   bool Op0IsKill = hasTrivialKill(I->getOperand(0));
1457 
1458   // First, try to perform the bitcast by inserting a reg-reg copy.
1459   Register ResultReg;
1460   if (SrcVT == DstVT) {
1461     const TargetRegisterClass *SrcClass = TLI.getRegClassFor(SrcVT);
1462     const TargetRegisterClass *DstClass = TLI.getRegClassFor(DstVT);
1463     // Don't attempt a cross-class copy. It will likely fail.
1464     if (SrcClass == DstClass) {
1465       ResultReg = createResultReg(DstClass);
1466       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1467               TII.get(TargetOpcode::COPY), ResultReg).addReg(Op0);
1468     }
1469   }
1470 
1471   // If the reg-reg copy failed, select a BITCAST opcode.
1472   if (!ResultReg)
1473     ResultReg = fastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0, Op0IsKill);
1474 
1475   if (!ResultReg)
1476     return false;
1477 
1478   updateValueMap(I, ResultReg);
1479   return true;
1480 }
1481 
1482 bool FastISel::selectFreeze(const User *I) {
1483   Register Reg = getRegForValue(I->getOperand(0));
1484   if (!Reg)
1485     // Unhandled operand.
1486     return false;
1487 
1488   EVT ETy = TLI.getValueType(DL, I->getOperand(0)->getType());
1489   if (ETy == MVT::Other || !TLI.isTypeLegal(ETy))
1490     // Unhandled type, bail out.
1491     return false;
1492 
1493   MVT Ty = ETy.getSimpleVT();
1494   const TargetRegisterClass *TyRegClass = TLI.getRegClassFor(Ty);
1495   Register ResultReg = createResultReg(TyRegClass);
1496   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1497           TII.get(TargetOpcode::COPY), ResultReg).addReg(Reg);
1498 
1499   updateValueMap(I, ResultReg);
1500   return true;
1501 }
1502 
1503 // Remove local value instructions starting from the instruction after
1504 // SavedLastLocalValue to the current function insert point.
1505 void FastISel::removeDeadLocalValueCode(MachineInstr *SavedLastLocalValue)
1506 {
1507   MachineInstr *CurLastLocalValue = getLastLocalValue();
1508   if (CurLastLocalValue != SavedLastLocalValue) {
1509     // Find the first local value instruction to be deleted.
1510     // This is the instruction after SavedLastLocalValue if it is non-NULL.
1511     // Otherwise it's the first instruction in the block.
1512     MachineBasicBlock::iterator FirstDeadInst(SavedLastLocalValue);
1513     if (SavedLastLocalValue)
1514       ++FirstDeadInst;
1515     else
1516       FirstDeadInst = FuncInfo.MBB->getFirstNonPHI();
1517     setLastLocalValue(SavedLastLocalValue);
1518     removeDeadCode(FirstDeadInst, FuncInfo.InsertPt);
1519   }
1520 }
1521 
1522 bool FastISel::selectInstruction(const Instruction *I) {
1523   // Flush the local value map before starting each instruction.
1524   // This improves locality and debugging, and can reduce spills.
1525   // Reuse of values across IR instructions is relatively uncommon.
1526   flushLocalValueMap();
1527 
1528   MachineInstr *SavedLastLocalValue = getLastLocalValue();
1529   // Just before the terminator instruction, insert instructions to
1530   // feed PHI nodes in successor blocks.
1531   if (I->isTerminator()) {
1532     if (!handlePHINodesInSuccessorBlocks(I->getParent())) {
1533       // PHI node handling may have generated local value instructions,
1534       // even though it failed to handle all PHI nodes.
1535       // We remove these instructions because SelectionDAGISel will generate
1536       // them again.
1537       removeDeadLocalValueCode(SavedLastLocalValue);
1538       return false;
1539     }
1540   }
1541 
1542   // FastISel does not handle any operand bundles except OB_funclet.
1543   if (auto *Call = dyn_cast<CallBase>(I))
1544     for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i)
1545       if (Call->getOperandBundleAt(i).getTagID() != LLVMContext::OB_funclet)
1546         return false;
1547 
1548   DbgLoc = I->getDebugLoc();
1549 
1550   SavedInsertPt = FuncInfo.InsertPt;
1551 
1552   if (const auto *Call = dyn_cast<CallInst>(I)) {
1553     const Function *F = Call->getCalledFunction();
1554     LibFunc Func;
1555 
1556     // As a special case, don't handle calls to builtin library functions that
1557     // may be translated directly to target instructions.
1558     if (F && !F->hasLocalLinkage() && F->hasName() &&
1559         LibInfo->getLibFunc(F->getName(), Func) &&
1560         LibInfo->hasOptimizedCodeGen(Func))
1561       return false;
1562 
1563     // Don't handle Intrinsic::trap if a trap function is specified.
1564     if (F && F->getIntrinsicID() == Intrinsic::trap &&
1565         Call->hasFnAttr("trap-func-name"))
1566       return false;
1567   }
1568 
1569   // First, try doing target-independent selection.
1570   if (!SkipTargetIndependentISel) {
1571     if (selectOperator(I, I->getOpcode())) {
1572       ++NumFastIselSuccessIndependent;
1573       DbgLoc = DebugLoc();
1574       return true;
1575     }
1576     // Remove dead code.
1577     recomputeInsertPt();
1578     if (SavedInsertPt != FuncInfo.InsertPt)
1579       removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
1580     SavedInsertPt = FuncInfo.InsertPt;
1581   }
1582   // Next, try calling the target to attempt to handle the instruction.
1583   if (fastSelectInstruction(I)) {
1584     ++NumFastIselSuccessTarget;
1585     DbgLoc = DebugLoc();
1586     return true;
1587   }
1588   // Remove dead code.
1589   recomputeInsertPt();
1590   if (SavedInsertPt != FuncInfo.InsertPt)
1591     removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
1592 
1593   DbgLoc = DebugLoc();
1594   // Undo phi node updates, because they will be added again by SelectionDAG.
1595   if (I->isTerminator()) {
1596     // PHI node handling may have generated local value instructions.
1597     // We remove them because SelectionDAGISel will generate them again.
1598     removeDeadLocalValueCode(SavedLastLocalValue);
1599     FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
1600   }
1601   return false;
1602 }
1603 
1604 /// Emit an unconditional branch to the given block, unless it is the immediate
1605 /// (fall-through) successor, and update the CFG.
1606 void FastISel::fastEmitBranch(MachineBasicBlock *MSucc,
1607                               const DebugLoc &DbgLoc) {
1608   if (FuncInfo.MBB->getBasicBlock()->sizeWithoutDebug() > 1 &&
1609       FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
1610     // For more accurate line information if this is the only non-debug
1611     // instruction in the block then emit it, otherwise we have the
1612     // unconditional fall-through case, which needs no instructions.
1613   } else {
1614     // The unconditional branch case.
1615     TII.insertBranch(*FuncInfo.MBB, MSucc, nullptr,
1616                      SmallVector<MachineOperand, 0>(), DbgLoc);
1617   }
1618   if (FuncInfo.BPI) {
1619     auto BranchProbability = FuncInfo.BPI->getEdgeProbability(
1620         FuncInfo.MBB->getBasicBlock(), MSucc->getBasicBlock());
1621     FuncInfo.MBB->addSuccessor(MSucc, BranchProbability);
1622   } else
1623     FuncInfo.MBB->addSuccessorWithoutProb(MSucc);
1624 }
1625 
1626 void FastISel::finishCondBranch(const BasicBlock *BranchBB,
1627                                 MachineBasicBlock *TrueMBB,
1628                                 MachineBasicBlock *FalseMBB) {
1629   // Add TrueMBB as successor unless it is equal to the FalseMBB: This can
1630   // happen in degenerate IR and MachineIR forbids to have a block twice in the
1631   // successor/predecessor lists.
1632   if (TrueMBB != FalseMBB) {
1633     if (FuncInfo.BPI) {
1634       auto BranchProbability =
1635           FuncInfo.BPI->getEdgeProbability(BranchBB, TrueMBB->getBasicBlock());
1636       FuncInfo.MBB->addSuccessor(TrueMBB, BranchProbability);
1637     } else
1638       FuncInfo.MBB->addSuccessorWithoutProb(TrueMBB);
1639   }
1640 
1641   fastEmitBranch(FalseMBB, DbgLoc);
1642 }
1643 
1644 /// Emit an FNeg operation.
1645 bool FastISel::selectFNeg(const User *I, const Value *In) {
1646   Register OpReg = getRegForValue(In);
1647   if (!OpReg)
1648     return false;
1649   bool OpRegIsKill = hasTrivialKill(In);
1650 
1651   // If the target has ISD::FNEG, use it.
1652   EVT VT = TLI.getValueType(DL, I->getType());
1653   Register ResultReg = fastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(), ISD::FNEG,
1654                                   OpReg, OpRegIsKill);
1655   if (ResultReg) {
1656     updateValueMap(I, ResultReg);
1657     return true;
1658   }
1659 
1660   // Bitcast the value to integer, twiddle the sign bit with xor,
1661   // and then bitcast it back to floating-point.
1662   if (VT.getSizeInBits() > 64)
1663     return false;
1664   EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
1665   if (!TLI.isTypeLegal(IntVT))
1666     return false;
1667 
1668   Register IntReg = fastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
1669                                ISD::BITCAST, OpReg, OpRegIsKill);
1670   if (!IntReg)
1671     return false;
1672 
1673   Register IntResultReg = fastEmit_ri_(
1674       IntVT.getSimpleVT(), ISD::XOR, IntReg, /*Op0IsKill=*/true,
1675       UINT64_C(1) << (VT.getSizeInBits() - 1), IntVT.getSimpleVT());
1676   if (!IntResultReg)
1677     return false;
1678 
1679   ResultReg = fastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(), ISD::BITCAST,
1680                          IntResultReg, /*Op0IsKill=*/true);
1681   if (!ResultReg)
1682     return false;
1683 
1684   updateValueMap(I, ResultReg);
1685   return true;
1686 }
1687 
1688 bool FastISel::selectExtractValue(const User *U) {
1689   const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
1690   if (!EVI)
1691     return false;
1692 
1693   // Make sure we only try to handle extracts with a legal result.  But also
1694   // allow i1 because it's easy.
1695   EVT RealVT = TLI.getValueType(DL, EVI->getType(), /*AllowUnknown=*/true);
1696   if (!RealVT.isSimple())
1697     return false;
1698   MVT VT = RealVT.getSimpleVT();
1699   if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
1700     return false;
1701 
1702   const Value *Op0 = EVI->getOperand(0);
1703   Type *AggTy = Op0->getType();
1704 
1705   // Get the base result register.
1706   unsigned ResultReg;
1707   DenseMap<const Value *, Register>::iterator I = FuncInfo.ValueMap.find(Op0);
1708   if (I != FuncInfo.ValueMap.end())
1709     ResultReg = I->second;
1710   else if (isa<Instruction>(Op0))
1711     ResultReg = FuncInfo.InitializeRegForValue(Op0);
1712   else
1713     return false; // fast-isel can't handle aggregate constants at the moment
1714 
1715   // Get the actual result register, which is an offset from the base register.
1716   unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
1717 
1718   SmallVector<EVT, 4> AggValueVTs;
1719   ComputeValueVTs(TLI, DL, AggTy, AggValueVTs);
1720 
1721   for (unsigned i = 0; i < VTIndex; i++)
1722     ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
1723 
1724   updateValueMap(EVI, ResultReg);
1725   return true;
1726 }
1727 
1728 bool FastISel::selectOperator(const User *I, unsigned Opcode) {
1729   switch (Opcode) {
1730   case Instruction::Add:
1731     return selectBinaryOp(I, ISD::ADD);
1732   case Instruction::FAdd:
1733     return selectBinaryOp(I, ISD::FADD);
1734   case Instruction::Sub:
1735     return selectBinaryOp(I, ISD::SUB);
1736   case Instruction::FSub:
1737     return selectBinaryOp(I, ISD::FSUB);
1738   case Instruction::Mul:
1739     return selectBinaryOp(I, ISD::MUL);
1740   case Instruction::FMul:
1741     return selectBinaryOp(I, ISD::FMUL);
1742   case Instruction::SDiv:
1743     return selectBinaryOp(I, ISD::SDIV);
1744   case Instruction::UDiv:
1745     return selectBinaryOp(I, ISD::UDIV);
1746   case Instruction::FDiv:
1747     return selectBinaryOp(I, ISD::FDIV);
1748   case Instruction::SRem:
1749     return selectBinaryOp(I, ISD::SREM);
1750   case Instruction::URem:
1751     return selectBinaryOp(I, ISD::UREM);
1752   case Instruction::FRem:
1753     return selectBinaryOp(I, ISD::FREM);
1754   case Instruction::Shl:
1755     return selectBinaryOp(I, ISD::SHL);
1756   case Instruction::LShr:
1757     return selectBinaryOp(I, ISD::SRL);
1758   case Instruction::AShr:
1759     return selectBinaryOp(I, ISD::SRA);
1760   case Instruction::And:
1761     return selectBinaryOp(I, ISD::AND);
1762   case Instruction::Or:
1763     return selectBinaryOp(I, ISD::OR);
1764   case Instruction::Xor:
1765     return selectBinaryOp(I, ISD::XOR);
1766 
1767   case Instruction::FNeg:
1768     return selectFNeg(I, I->getOperand(0));
1769 
1770   case Instruction::GetElementPtr:
1771     return selectGetElementPtr(I);
1772 
1773   case Instruction::Br: {
1774     const BranchInst *BI = cast<BranchInst>(I);
1775 
1776     if (BI->isUnconditional()) {
1777       const BasicBlock *LLVMSucc = BI->getSuccessor(0);
1778       MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
1779       fastEmitBranch(MSucc, BI->getDebugLoc());
1780       return true;
1781     }
1782 
1783     // Conditional branches are not handed yet.
1784     // Halt "fast" selection and bail.
1785     return false;
1786   }
1787 
1788   case Instruction::Unreachable:
1789     if (TM.Options.TrapUnreachable)
1790       return fastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0;
1791     else
1792       return true;
1793 
1794   case Instruction::Alloca:
1795     // FunctionLowering has the static-sized case covered.
1796     if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
1797       return true;
1798 
1799     // Dynamic-sized alloca is not handled yet.
1800     return false;
1801 
1802   case Instruction::Call:
1803     // On AIX, call lowering uses the DAG-ISEL path currently so that the
1804     // callee of the direct function call instruction will be mapped to the
1805     // symbol for the function's entry point, which is distinct from the
1806     // function descriptor symbol. The latter is the symbol whose XCOFF symbol
1807     // name is the C-linkage name of the source level function.
1808     if (TM.getTargetTriple().isOSAIX())
1809       return false;
1810     return selectCall(I);
1811 
1812   case Instruction::BitCast:
1813     return selectBitCast(I);
1814 
1815   case Instruction::FPToSI:
1816     return selectCast(I, ISD::FP_TO_SINT);
1817   case Instruction::ZExt:
1818     return selectCast(I, ISD::ZERO_EXTEND);
1819   case Instruction::SExt:
1820     return selectCast(I, ISD::SIGN_EXTEND);
1821   case Instruction::Trunc:
1822     return selectCast(I, ISD::TRUNCATE);
1823   case Instruction::SIToFP:
1824     return selectCast(I, ISD::SINT_TO_FP);
1825 
1826   case Instruction::IntToPtr: // Deliberate fall-through.
1827   case Instruction::PtrToInt: {
1828     EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
1829     EVT DstVT = TLI.getValueType(DL, I->getType());
1830     if (DstVT.bitsGT(SrcVT))
1831       return selectCast(I, ISD::ZERO_EXTEND);
1832     if (DstVT.bitsLT(SrcVT))
1833       return selectCast(I, ISD::TRUNCATE);
1834     Register Reg = getRegForValue(I->getOperand(0));
1835     if (!Reg)
1836       return false;
1837     updateValueMap(I, Reg);
1838     return true;
1839   }
1840 
1841   case Instruction::ExtractValue:
1842     return selectExtractValue(I);
1843 
1844   case Instruction::Freeze:
1845     return selectFreeze(I);
1846 
1847   case Instruction::PHI:
1848     llvm_unreachable("FastISel shouldn't visit PHI nodes!");
1849 
1850   default:
1851     // Unhandled instruction. Halt "fast" selection and bail.
1852     return false;
1853   }
1854 }
1855 
1856 FastISel::FastISel(FunctionLoweringInfo &FuncInfo,
1857                    const TargetLibraryInfo *LibInfo,
1858                    bool SkipTargetIndependentISel)
1859     : FuncInfo(FuncInfo), MF(FuncInfo.MF), MRI(FuncInfo.MF->getRegInfo()),
1860       MFI(FuncInfo.MF->getFrameInfo()), MCP(*FuncInfo.MF->getConstantPool()),
1861       TM(FuncInfo.MF->getTarget()), DL(MF->getDataLayout()),
1862       TII(*MF->getSubtarget().getInstrInfo()),
1863       TLI(*MF->getSubtarget().getTargetLowering()),
1864       TRI(*MF->getSubtarget().getRegisterInfo()), LibInfo(LibInfo),
1865       SkipTargetIndependentISel(SkipTargetIndependentISel),
1866       LastLocalValue(nullptr), EmitStartPt(nullptr) {}
1867 
1868 FastISel::~FastISel() = default;
1869 
1870 bool FastISel::fastLowerArguments() { return false; }
1871 
1872 bool FastISel::fastLowerCall(CallLoweringInfo & /*CLI*/) { return false; }
1873 
1874 bool FastISel::fastLowerIntrinsicCall(const IntrinsicInst * /*II*/) {
1875   return false;
1876 }
1877 
1878 unsigned FastISel::fastEmit_(MVT, MVT, unsigned) { return 0; }
1879 
1880 unsigned FastISel::fastEmit_r(MVT, MVT, unsigned, unsigned /*Op0*/,
1881                               bool /*Op0IsKill*/) {
1882   return 0;
1883 }
1884 
1885 unsigned FastISel::fastEmit_rr(MVT, MVT, unsigned, unsigned /*Op0*/,
1886                                bool /*Op0IsKill*/, unsigned /*Op1*/,
1887                                bool /*Op1IsKill*/) {
1888   return 0;
1889 }
1890 
1891 unsigned FastISel::fastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
1892   return 0;
1893 }
1894 
1895 unsigned FastISel::fastEmit_f(MVT, MVT, unsigned,
1896                               const ConstantFP * /*FPImm*/) {
1897   return 0;
1898 }
1899 
1900 unsigned FastISel::fastEmit_ri(MVT, MVT, unsigned, unsigned /*Op0*/,
1901                                bool /*Op0IsKill*/, uint64_t /*Imm*/) {
1902   return 0;
1903 }
1904 
1905 /// This method is a wrapper of fastEmit_ri. It first tries to emit an
1906 /// instruction with an immediate operand using fastEmit_ri.
1907 /// If that fails, it materializes the immediate into a register and try
1908 /// fastEmit_rr instead.
1909 Register FastISel::fastEmit_ri_(MVT VT, unsigned Opcode, unsigned Op0,
1910                                 bool Op0IsKill, uint64_t Imm, MVT ImmType) {
1911   // If this is a multiply by a power of two, emit this as a shift left.
1912   if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
1913     Opcode = ISD::SHL;
1914     Imm = Log2_64(Imm);
1915   } else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
1916     // div x, 8 -> srl x, 3
1917     Opcode = ISD::SRL;
1918     Imm = Log2_64(Imm);
1919   }
1920 
1921   // Horrible hack (to be removed), check to make sure shift amounts are
1922   // in-range.
1923   if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
1924       Imm >= VT.getSizeInBits())
1925     return 0;
1926 
1927   // First check if immediate type is legal. If not, we can't use the ri form.
1928   Register ResultReg = fastEmit_ri(VT, VT, Opcode, Op0, Op0IsKill, Imm);
1929   if (ResultReg)
1930     return ResultReg;
1931   Register MaterialReg = fastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
1932   bool IsImmKill = true;
1933   if (!MaterialReg) {
1934     // This is a bit ugly/slow, but failing here means falling out of
1935     // fast-isel, which would be very slow.
1936     IntegerType *ITy =
1937         IntegerType::get(FuncInfo.Fn->getContext(), VT.getSizeInBits());
1938     MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
1939     if (!MaterialReg)
1940       return 0;
1941     // FIXME: If the materialized register here has no uses yet then this
1942     // will be the first use and we should be able to mark it as killed.
1943     // However, the local value area for materialising constant expressions
1944     // grows down, not up, which means that any constant expressions we generate
1945     // later which also use 'Imm' could be after this instruction and therefore
1946     // after this kill.
1947     IsImmKill = false;
1948   }
1949   return fastEmit_rr(VT, VT, Opcode, Op0, Op0IsKill, MaterialReg, IsImmKill);
1950 }
1951 
1952 Register FastISel::createResultReg(const TargetRegisterClass *RC) {
1953   return MRI.createVirtualRegister(RC);
1954 }
1955 
1956 Register FastISel::constrainOperandRegClass(const MCInstrDesc &II, Register Op,
1957                                             unsigned OpNum) {
1958   if (Op.isVirtual()) {
1959     const TargetRegisterClass *RegClass =
1960         TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF);
1961     if (!MRI.constrainRegClass(Op, RegClass)) {
1962       // If it's not legal to COPY between the register classes, something
1963       // has gone very wrong before we got here.
1964       Register NewOp = createResultReg(RegClass);
1965       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1966               TII.get(TargetOpcode::COPY), NewOp).addReg(Op);
1967       return NewOp;
1968     }
1969   }
1970   return Op;
1971 }
1972 
1973 Register FastISel::fastEmitInst_(unsigned MachineInstOpcode,
1974                                  const TargetRegisterClass *RC) {
1975   Register ResultReg = createResultReg(RC);
1976   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1977 
1978   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg);
1979   return ResultReg;
1980 }
1981 
1982 Register FastISel::fastEmitInst_r(unsigned MachineInstOpcode,
1983                                   const TargetRegisterClass *RC, unsigned Op0,
1984                                   bool Op0IsKill) {
1985   const MCInstrDesc &II = TII.get(MachineInstOpcode);
1986 
1987   Register ResultReg = createResultReg(RC);
1988   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
1989 
1990   if (II.getNumDefs() >= 1)
1991     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1992         .addReg(Op0, getKillRegState(Op0IsKill));
1993   else {
1994     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1995         .addReg(Op0, getKillRegState(Op0IsKill));
1996     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1997             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
1998   }
1999 
2000   return ResultReg;
2001 }
2002 
2003 Register FastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
2004                                    const TargetRegisterClass *RC, unsigned Op0,
2005                                    bool Op0IsKill, unsigned Op1,
2006                                    bool Op1IsKill) {
2007   const MCInstrDesc &II = TII.get(MachineInstOpcode);
2008 
2009   Register ResultReg = createResultReg(RC);
2010   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
2011   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
2012 
2013   if (II.getNumDefs() >= 1)
2014     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
2015         .addReg(Op0, getKillRegState(Op0IsKill))
2016         .addReg(Op1, getKillRegState(Op1IsKill));
2017   else {
2018     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2019         .addReg(Op0, getKillRegState(Op0IsKill))
2020         .addReg(Op1, getKillRegState(Op1IsKill));
2021     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2022             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
2023   }
2024   return ResultReg;
2025 }
2026 
2027 Register FastISel::fastEmitInst_rrr(unsigned MachineInstOpcode,
2028                                     const TargetRegisterClass *RC, unsigned Op0,
2029                                     bool Op0IsKill, unsigned Op1,
2030                                     bool Op1IsKill, unsigned Op2,
2031                                     bool Op2IsKill) {
2032   const MCInstrDesc &II = TII.get(MachineInstOpcode);
2033 
2034   Register ResultReg = createResultReg(RC);
2035   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
2036   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
2037   Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
2038 
2039   if (II.getNumDefs() >= 1)
2040     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
2041         .addReg(Op0, getKillRegState(Op0IsKill))
2042         .addReg(Op1, getKillRegState(Op1IsKill))
2043         .addReg(Op2, getKillRegState(Op2IsKill));
2044   else {
2045     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2046         .addReg(Op0, getKillRegState(Op0IsKill))
2047         .addReg(Op1, getKillRegState(Op1IsKill))
2048         .addReg(Op2, getKillRegState(Op2IsKill));
2049     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2050             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
2051   }
2052   return ResultReg;
2053 }
2054 
2055 Register FastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
2056                                    const TargetRegisterClass *RC, unsigned Op0,
2057                                    bool Op0IsKill, uint64_t Imm) {
2058   const MCInstrDesc &II = TII.get(MachineInstOpcode);
2059 
2060   Register ResultReg = createResultReg(RC);
2061   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
2062 
2063   if (II.getNumDefs() >= 1)
2064     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
2065         .addReg(Op0, getKillRegState(Op0IsKill))
2066         .addImm(Imm);
2067   else {
2068     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2069         .addReg(Op0, getKillRegState(Op0IsKill))
2070         .addImm(Imm);
2071     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2072             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
2073   }
2074   return ResultReg;
2075 }
2076 
2077 Register FastISel::fastEmitInst_rii(unsigned MachineInstOpcode,
2078                                     const TargetRegisterClass *RC, unsigned Op0,
2079                                     bool Op0IsKill, uint64_t Imm1,
2080                                     uint64_t Imm2) {
2081   const MCInstrDesc &II = TII.get(MachineInstOpcode);
2082 
2083   Register ResultReg = createResultReg(RC);
2084   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
2085 
2086   if (II.getNumDefs() >= 1)
2087     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
2088         .addReg(Op0, getKillRegState(Op0IsKill))
2089         .addImm(Imm1)
2090         .addImm(Imm2);
2091   else {
2092     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2093         .addReg(Op0, getKillRegState(Op0IsKill))
2094         .addImm(Imm1)
2095         .addImm(Imm2);
2096     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2097             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
2098   }
2099   return ResultReg;
2100 }
2101 
2102 Register FastISel::fastEmitInst_f(unsigned MachineInstOpcode,
2103                                   const TargetRegisterClass *RC,
2104                                   const ConstantFP *FPImm) {
2105   const MCInstrDesc &II = TII.get(MachineInstOpcode);
2106 
2107   Register ResultReg = createResultReg(RC);
2108 
2109   if (II.getNumDefs() >= 1)
2110     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
2111         .addFPImm(FPImm);
2112   else {
2113     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2114         .addFPImm(FPImm);
2115     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2116             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
2117   }
2118   return ResultReg;
2119 }
2120 
2121 Register FastISel::fastEmitInst_rri(unsigned MachineInstOpcode,
2122                                     const TargetRegisterClass *RC, unsigned Op0,
2123                                     bool Op0IsKill, unsigned Op1,
2124                                     bool Op1IsKill, uint64_t Imm) {
2125   const MCInstrDesc &II = TII.get(MachineInstOpcode);
2126 
2127   Register ResultReg = createResultReg(RC);
2128   Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
2129   Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
2130 
2131   if (II.getNumDefs() >= 1)
2132     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
2133         .addReg(Op0, getKillRegState(Op0IsKill))
2134         .addReg(Op1, getKillRegState(Op1IsKill))
2135         .addImm(Imm);
2136   else {
2137     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2138         .addReg(Op0, getKillRegState(Op0IsKill))
2139         .addReg(Op1, getKillRegState(Op1IsKill))
2140         .addImm(Imm);
2141     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2142             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
2143   }
2144   return ResultReg;
2145 }
2146 
2147 Register FastISel::fastEmitInst_i(unsigned MachineInstOpcode,
2148                                   const TargetRegisterClass *RC, uint64_t Imm) {
2149   Register ResultReg = createResultReg(RC);
2150   const MCInstrDesc &II = TII.get(MachineInstOpcode);
2151 
2152   if (II.getNumDefs() >= 1)
2153     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
2154         .addImm(Imm);
2155   else {
2156     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm);
2157     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2158             TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
2159   }
2160   return ResultReg;
2161 }
2162 
2163 Register FastISel::fastEmitInst_extractsubreg(MVT RetVT, unsigned Op0,
2164                                               bool Op0IsKill, uint32_t Idx) {
2165   Register ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
2166   assert(Register::isVirtualRegister(Op0) &&
2167          "Cannot yet extract from physregs");
2168   const TargetRegisterClass *RC = MRI.getRegClass(Op0);
2169   MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
2170   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
2171           ResultReg).addReg(Op0, getKillRegState(Op0IsKill), Idx);
2172   return ResultReg;
2173 }
2174 
2175 /// Emit MachineInstrs to compute the value of Op with all but the least
2176 /// significant bit set to zero.
2177 Register FastISel::fastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill) {
2178   return fastEmit_ri(VT, VT, ISD::AND, Op0, Op0IsKill, 1);
2179 }
2180 
2181 /// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
2182 /// Emit code to ensure constants are copied into registers when needed.
2183 /// Remember the virtual registers that need to be added to the Machine PHI
2184 /// nodes as input.  We cannot just directly add them, because expansion
2185 /// might result in multiple MBB's for one BB.  As such, the start of the
2186 /// BB might correspond to a different MBB than the end.
2187 bool FastISel::handlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
2188   const Instruction *TI = LLVMBB->getTerminator();
2189 
2190   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
2191   FuncInfo.OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
2192 
2193   // Check successor nodes' PHI nodes that expect a constant to be available
2194   // from this block.
2195   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2196     const BasicBlock *SuccBB = TI->getSuccessor(succ);
2197     if (!isa<PHINode>(SuccBB->begin()))
2198       continue;
2199     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
2200 
2201     // If this terminator has multiple identical successors (common for
2202     // switches), only handle each succ once.
2203     if (!SuccsHandled.insert(SuccMBB).second)
2204       continue;
2205 
2206     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
2207 
2208     // At this point we know that there is a 1-1 correspondence between LLVM PHI
2209     // nodes and Machine PHI nodes, but the incoming operands have not been
2210     // emitted yet.
2211     for (const PHINode &PN : SuccBB->phis()) {
2212       // Ignore dead phi's.
2213       if (PN.use_empty())
2214         continue;
2215 
2216       // Only handle legal types. Two interesting things to note here. First,
2217       // by bailing out early, we may leave behind some dead instructions,
2218       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
2219       // own moves. Second, this check is necessary because FastISel doesn't
2220       // use CreateRegs to create registers, so it always creates
2221       // exactly one register for each non-void instruction.
2222       EVT VT = TLI.getValueType(DL, PN.getType(), /*AllowUnknown=*/true);
2223       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
2224         // Handle integer promotions, though, because they're common and easy.
2225         if (!(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)) {
2226           FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
2227           return false;
2228         }
2229       }
2230 
2231       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
2232 
2233       // Set the DebugLoc for the copy. Use the location of the operand if
2234       // there is one; otherwise no location, flushLocalValueMap will fix it.
2235       DbgLoc = DebugLoc();
2236       if (const auto *Inst = dyn_cast<Instruction>(PHIOp))
2237         DbgLoc = Inst->getDebugLoc();
2238 
2239       Register Reg = getRegForValue(PHIOp);
2240       if (!Reg) {
2241         FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
2242         return false;
2243       }
2244       FuncInfo.PHINodesToUpdate.push_back(std::make_pair(&*MBBI++, Reg));
2245       DbgLoc = DebugLoc();
2246     }
2247   }
2248 
2249   return true;
2250 }
2251 
2252 bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) {
2253   assert(LI->hasOneUse() &&
2254          "tryToFoldLoad expected a LoadInst with a single use");
2255   // We know that the load has a single use, but don't know what it is.  If it
2256   // isn't one of the folded instructions, then we can't succeed here.  Handle
2257   // this by scanning the single-use users of the load until we get to FoldInst.
2258   unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs.
2259 
2260   const Instruction *TheUser = LI->user_back();
2261   while (TheUser != FoldInst && // Scan up until we find FoldInst.
2262          // Stay in the right block.
2263          TheUser->getParent() == FoldInst->getParent() &&
2264          --MaxUsers) { // Don't scan too far.
2265     // If there are multiple or no uses of this instruction, then bail out.
2266     if (!TheUser->hasOneUse())
2267       return false;
2268 
2269     TheUser = TheUser->user_back();
2270   }
2271 
2272   // If we didn't find the fold instruction, then we failed to collapse the
2273   // sequence.
2274   if (TheUser != FoldInst)
2275     return false;
2276 
2277   // Don't try to fold volatile loads.  Target has to deal with alignment
2278   // constraints.
2279   if (LI->isVolatile())
2280     return false;
2281 
2282   // Figure out which vreg this is going into.  If there is no assigned vreg yet
2283   // then there actually was no reference to it.  Perhaps the load is referenced
2284   // by a dead instruction.
2285   Register LoadReg = getRegForValue(LI);
2286   if (!LoadReg)
2287     return false;
2288 
2289   // We can't fold if this vreg has no uses or more than one use.  Multiple uses
2290   // may mean that the instruction got lowered to multiple MIs, or the use of
2291   // the loaded value ended up being multiple operands of the result.
2292   if (!MRI.hasOneUse(LoadReg))
2293     return false;
2294 
2295   MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg);
2296   MachineInstr *User = RI->getParent();
2297 
2298   // Set the insertion point properly.  Folding the load can cause generation of
2299   // other random instructions (like sign extends) for addressing modes; make
2300   // sure they get inserted in a logical place before the new instruction.
2301   FuncInfo.InsertPt = User;
2302   FuncInfo.MBB = User->getParent();
2303 
2304   // Ask the target to try folding the load.
2305   return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI);
2306 }
2307 
2308 bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) {
2309   // Must be an add.
2310   if (!isa<AddOperator>(Add))
2311     return false;
2312   // Type size needs to match.
2313   if (DL.getTypeSizeInBits(GEP->getType()) !=
2314       DL.getTypeSizeInBits(Add->getType()))
2315     return false;
2316   // Must be in the same basic block.
2317   if (isa<Instruction>(Add) &&
2318       FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB)
2319     return false;
2320   // Must have a constant operand.
2321   return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1));
2322 }
2323 
2324 MachineMemOperand *
2325 FastISel::createMachineMemOperandFor(const Instruction *I) const {
2326   const Value *Ptr;
2327   Type *ValTy;
2328   MaybeAlign Alignment;
2329   MachineMemOperand::Flags Flags;
2330   bool IsVolatile;
2331 
2332   if (const auto *LI = dyn_cast<LoadInst>(I)) {
2333     Alignment = LI->getAlign();
2334     IsVolatile = LI->isVolatile();
2335     Flags = MachineMemOperand::MOLoad;
2336     Ptr = LI->getPointerOperand();
2337     ValTy = LI->getType();
2338   } else if (const auto *SI = dyn_cast<StoreInst>(I)) {
2339     Alignment = SI->getAlign();
2340     IsVolatile = SI->isVolatile();
2341     Flags = MachineMemOperand::MOStore;
2342     Ptr = SI->getPointerOperand();
2343     ValTy = SI->getValueOperand()->getType();
2344   } else
2345     return nullptr;
2346 
2347   bool IsNonTemporal = I->hasMetadata(LLVMContext::MD_nontemporal);
2348   bool IsInvariant = I->hasMetadata(LLVMContext::MD_invariant_load);
2349   bool IsDereferenceable = I->hasMetadata(LLVMContext::MD_dereferenceable);
2350   const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range);
2351 
2352   AAMDNodes AAInfo;
2353   I->getAAMetadata(AAInfo);
2354 
2355   if (!Alignment) // Ensure that codegen never sees alignment 0.
2356     Alignment = DL.getABITypeAlign(ValTy);
2357 
2358   unsigned Size = DL.getTypeStoreSize(ValTy);
2359 
2360   if (IsVolatile)
2361     Flags |= MachineMemOperand::MOVolatile;
2362   if (IsNonTemporal)
2363     Flags |= MachineMemOperand::MONonTemporal;
2364   if (IsDereferenceable)
2365     Flags |= MachineMemOperand::MODereferenceable;
2366   if (IsInvariant)
2367     Flags |= MachineMemOperand::MOInvariant;
2368 
2369   return FuncInfo.MF->getMachineMemOperand(MachinePointerInfo(Ptr), Flags, Size,
2370                                            *Alignment, AAInfo, Ranges);
2371 }
2372 
2373 CmpInst::Predicate FastISel::optimizeCmpPredicate(const CmpInst *CI) const {
2374   // If both operands are the same, then try to optimize or fold the cmp.
2375   CmpInst::Predicate Predicate = CI->getPredicate();
2376   if (CI->getOperand(0) != CI->getOperand(1))
2377     return Predicate;
2378 
2379   switch (Predicate) {
2380   default: llvm_unreachable("Invalid predicate!");
2381   case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
2382   case CmpInst::FCMP_OEQ:   Predicate = CmpInst::FCMP_ORD;   break;
2383   case CmpInst::FCMP_OGT:   Predicate = CmpInst::FCMP_FALSE; break;
2384   case CmpInst::FCMP_OGE:   Predicate = CmpInst::FCMP_ORD;   break;
2385   case CmpInst::FCMP_OLT:   Predicate = CmpInst::FCMP_FALSE; break;
2386   case CmpInst::FCMP_OLE:   Predicate = CmpInst::FCMP_ORD;   break;
2387   case CmpInst::FCMP_ONE:   Predicate = CmpInst::FCMP_FALSE; break;
2388   case CmpInst::FCMP_ORD:   Predicate = CmpInst::FCMP_ORD;   break;
2389   case CmpInst::FCMP_UNO:   Predicate = CmpInst::FCMP_UNO;   break;
2390   case CmpInst::FCMP_UEQ:   Predicate = CmpInst::FCMP_TRUE;  break;
2391   case CmpInst::FCMP_UGT:   Predicate = CmpInst::FCMP_UNO;   break;
2392   case CmpInst::FCMP_UGE:   Predicate = CmpInst::FCMP_TRUE;  break;
2393   case CmpInst::FCMP_ULT:   Predicate = CmpInst::FCMP_UNO;   break;
2394   case CmpInst::FCMP_ULE:   Predicate = CmpInst::FCMP_TRUE;  break;
2395   case CmpInst::FCMP_UNE:   Predicate = CmpInst::FCMP_UNO;   break;
2396   case CmpInst::FCMP_TRUE:  Predicate = CmpInst::FCMP_TRUE;  break;
2397 
2398   case CmpInst::ICMP_EQ:    Predicate = CmpInst::FCMP_TRUE;  break;
2399   case CmpInst::ICMP_NE:    Predicate = CmpInst::FCMP_FALSE; break;
2400   case CmpInst::ICMP_UGT:   Predicate = CmpInst::FCMP_FALSE; break;
2401   case CmpInst::ICMP_UGE:   Predicate = CmpInst::FCMP_TRUE;  break;
2402   case CmpInst::ICMP_ULT:   Predicate = CmpInst::FCMP_FALSE; break;
2403   case CmpInst::ICMP_ULE:   Predicate = CmpInst::FCMP_TRUE;  break;
2404   case CmpInst::ICMP_SGT:   Predicate = CmpInst::FCMP_FALSE; break;
2405   case CmpInst::ICMP_SGE:   Predicate = CmpInst::FCMP_TRUE;  break;
2406   case CmpInst::ICMP_SLT:   Predicate = CmpInst::FCMP_FALSE; break;
2407   case CmpInst::ICMP_SLE:   Predicate = CmpInst::FCMP_TRUE;  break;
2408   }
2409 
2410   return Predicate;
2411 }
2412