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