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