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