LLVM 24.0.0git
IRTranslator.cpp
Go to the documentation of this file.
1//===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==//
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/// \file
9/// This file implements the IRTranslator class.
10//===----------------------------------------------------------------------===//
11
14#include "llvm/ADT/STLExtras.h"
15#include "llvm/ADT/ScopeExit.h"
20#include "llvm/Analysis/Loads.h"
55#include "llvm/IR/Analysis.h"
56#include "llvm/IR/BasicBlock.h"
57#include "llvm/IR/CFG.h"
58#include "llvm/IR/Constant.h"
59#include "llvm/IR/Constants.h"
60#include "llvm/IR/DataLayout.h"
63#include "llvm/IR/Function.h"
65#include "llvm/IR/InlineAsm.h"
66#include "llvm/IR/InstrTypes.h"
69#include "llvm/IR/Intrinsics.h"
70#include "llvm/IR/IntrinsicsAMDGPU.h"
71#include "llvm/IR/LLVMContext.h"
72#include "llvm/IR/Metadata.h"
73#include "llvm/IR/Module.h"
75#include "llvm/IR/Statepoint.h"
76#include "llvm/IR/Type.h"
77#include "llvm/IR/User.h"
78#include "llvm/IR/Value.h"
80#include "llvm/MC/MCContext.h"
81#include "llvm/Pass.h"
84#include "llvm/Support/Debug.h"
91#include <algorithm>
92#include <cassert>
93#include <cstdint>
94#include <iterator>
95#include <optional>
96#include <string>
97#include <utility>
98#include <vector>
99
100#define DEBUG_TYPE "ir-translator"
101
102using namespace llvm;
103
104static cl::opt<bool>
105 EnableCSEInIRTranslator("enable-cse-in-ir-translator",
106 cl::desc("Should enable CSE in ir-translator"),
107 cl::init(false));
108
109namespace llvm {
110
112 /// Interface used to lower the everything related to calls.
113 const CallLowering *CLI = nullptr;
114
115 SSPLayoutInfo *SPInfo = nullptr;
116
117 /// This class contains the mapping between the Values to vreg related data.
118 class ValueToVRegInfo {
119 public:
120 ValueToVRegInfo() = default;
121
122 using VRegListT = SmallVector<Register, 1>;
123 using OffsetListT = SmallVector<uint64_t, 1>;
124
125 using const_vreg_iterator =
127 using const_offset_iterator =
129
130 inline const_vreg_iterator vregs_end() const { return ValToVRegs.end(); }
131
132 VRegListT *getVRegs(const Value &V) {
133 auto [It, Inserted] = ValToVRegs.try_emplace(&V);
134 if (!Inserted)
135 return It->second;
136
137 // We placement new using our fast allocator since we never try to free
138 // the vectors until translation is finished.
139 It->second = new (VRegAlloc.Allocate()) VRegListT();
140 return It->second;
141 }
142
143 OffsetListT *getOffsets(const Value &V) {
144 assert(V.getType()->isAggregateType() &&
145 "Offsets are for aggregate values");
146 auto [It, Inserted] = TypeToOffsets.try_emplace(V.getType());
147 if (!Inserted)
148 return It->second;
149
150 It->second = new (OffsetAlloc.Allocate()) OffsetListT();
151 return It->second;
152 }
153
154 const_vreg_iterator findVRegs(const Value &V) const {
155 return ValToVRegs.find(&V);
156 }
157
158 bool contains(const Value &V) const { return ValToVRegs.contains(&V); }
159
160 void reserveVRegs(unsigned NumValues) { ValToVRegs.reserve(NumValues); }
161
162 void reset() {
163 ValToVRegs.clear();
164 TypeToOffsets.clear();
165 VRegAlloc.DestroyAll();
166 OffsetAlloc.DestroyAll();
167 }
168
169 private:
172
173 // We store pointers to vectors here since references may be invalidated
174 // while we hold them if we stored the vectors directly.
177 };
178
179 /// Mapping of the values of the current LLVM IR function to the related
180 /// virtual registers and offsets.
181 ValueToVRegInfo VMap;
182
183 // One BasicBlock can be translated to multiple MachineBasicBlocks. For such
184 // BasicBlocks translated to multiple MachineBasicBlocks, MachinePreds retains
185 // a mapping between the edges arriving at the BasicBlock to the corresponding
186 // created MachineBasicBlocks. Some BasicBlocks that get translated to a
187 // single MachineBasicBlock may also end up in this Map.
188 using CFGEdge = std::pair<const BasicBlock *, const BasicBlock *>;
190
191 // List of stubbed PHI instructions, for values and basic blocks to be filled
192 // in once all MachineBasicBlocks have been created.
194 PendingPHIs;
195
196 /// Record of what frame index has been allocated to specified allocas for
197 /// this function.
199
200 SwiftErrorValueTracking SwiftError;
201
202 /// \name Methods for translating form LLVM IR to MachineInstr.
203 /// \see ::translate for general information on the translate methods.
204 /// @{
205
206 /// Translate \p Inst into its corresponding MachineInstr instruction(s).
207 /// Insert the newly translated instruction(s) right where the CurBuilder
208 /// is set.
209 ///
210 /// The general algorithm is:
211 /// 1. Look for a virtual register for each operand or
212 /// create one.
213 /// 2 Update the VMap accordingly.
214 /// 2.alt. For constant arguments, if they are compile time constants,
215 /// produce an immediate in the right operand and do not touch
216 /// ValToReg. Actually we will go with a virtual register for each
217 /// constants because it may be expensive to actually materialize the
218 /// constant. Moreover, if the constant spans on several instructions,
219 /// CSE may not catch them.
220 /// => Update ValToVReg and remember that we saw a constant in Constants.
221 /// We will materialize all the constants in finalize.
222 /// Note: we would need to do something so that we can recognize such operand
223 /// as constants.
224 /// 3. Create the generic instruction.
225 ///
226 /// \return true if the translation succeeded.
227 bool translate(const Instruction &Inst);
228
229 /// Materialize \p C into virtual-register \p Reg. The generic instructions
230 /// performing this materialization will be inserted into the entry block of
231 /// the function.
232 ///
233 /// \return true if the materialization succeeded.
234 bool translate(const Constant &C, Register Reg);
235
236 /// Examine any debug-info attached to the instruction (in the form of
237 /// DbgRecords) and translate it.
238 void translateDbgInfo(const Instruction &Inst, MachineIRBuilder &MIRBuilder);
239
240 /// Translate a debug-info record of a dbg.value into a DBG_* instruction.
241 /// Pass in all the contents of the record, rather than relying on how it's
242 /// stored.
243 void translateDbgValueRecord(Value *V, bool HasArgList,
244 const DILocalVariable *Variable,
246 const DebugLoc &DL,
247 MachineIRBuilder &MIRBuilder);
248
249 /// Translate a debug-info record of a dbg.declare into an indirect DBG_*
250 /// instruction. Pass in all the contents of the record, rather than relying
251 /// on how it's stored.
252 void translateDbgDeclareRecord(Value *Address, bool HasArgList,
253 const DILocalVariable *Variable,
255 const DebugLoc &DL,
256 MachineIRBuilder &MIRBuilder);
257
258 // Translate U as a copy of V.
259 bool translateCopy(const User &U, const Value &V,
260 MachineIRBuilder &MIRBuilder);
261 bool translateCopy(const User &U, Register Src, MachineIRBuilder &MIRBuilder);
262
263 /// Translate an LLVM bitcast into generic IR. Either a COPY or a G_BITCAST is
264 /// emitted.
265 bool translateBitCast(const User &U, MachineIRBuilder &MIRBuilder);
266
267 /// Translate an LLVM load instruction into generic IR.
268 bool translateLoad(const User &U, MachineIRBuilder &MIRBuilder);
269
270 /// Translate an LLVM store instruction into generic IR.
271 bool translateStore(const User &U, MachineIRBuilder &MIRBuilder);
272
273 /// Translate an LLVM string intrinsic (memcpy, memset, ...).
274 bool translateMemFunc(const CallInst &CI, MachineIRBuilder &MIRBuilder,
275 unsigned Opcode);
276
277 /// Translate an LLVM trap intrinsic (trap, debugtrap, ubsantrap).
278 bool translateTrap(const CallInst &U, MachineIRBuilder &MIRBuilder,
279 unsigned Opcode);
280
281 // Translate @llvm.vector.interleave2 and
282 // @llvm.vector.deinterleave2 intrinsics for fixed-width vector
283 // types into vector shuffles.
284 bool translateVectorInterleave2Intrinsic(const CallInst &CI,
285 MachineIRBuilder &MIRBuilder);
286 bool translateVectorDeinterleave2Intrinsic(const CallInst &CI,
287 MachineIRBuilder &MIRBuilder);
288
289 void getStackGuard(Register DstReg, MachineIRBuilder &MIRBuilder);
290
291 bool translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
292 MachineIRBuilder &MIRBuilder);
293 bool translateFixedPointIntrinsic(unsigned Op, const CallInst &CI,
294 MachineIRBuilder &MIRBuilder);
295
296 /// Helper function for translateSimpleIntrinsic.
297 /// \return The generic opcode for \p IntrinsicID if \p IntrinsicID is a
298 /// simple intrinsic (ceil, fabs, etc.). Otherwise, returns
299 /// Intrinsic::not_intrinsic.
300 unsigned getSimpleIntrinsicOpcode(Intrinsic::ID ID);
301
302 /// Translates the intrinsics defined in getSimpleIntrinsicOpcode.
303 /// \return true if the translation succeeded.
304 bool translateSimpleIntrinsic(const CallInst &CI, Intrinsic::ID ID,
305 MachineIRBuilder &MIRBuilder);
306
307 bool translateConstrainedFPIntrinsic(const ConstrainedFPIntrinsic &FPI,
308 MachineIRBuilder &MIRBuilder);
309
310 bool translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
311 MachineIRBuilder &MIRBuilder);
312
313 /// Returns the single livein physical register Arg was lowered to, if
314 /// possible.
315 std::optional<MCRegister> getArgPhysReg(Argument &Arg);
316
317 /// If debug-info targets an Argument and its expression is an EntryValue,
318 /// lower it as either an entry in the MF debug table (dbg.declare), or a
319 /// DBG_VALUE targeting the corresponding livein register for that Argument
320 /// (dbg.value).
321 bool translateIfEntryValueArgument(bool isDeclare, Value *Arg,
322 const DILocalVariable *Var,
323 const DIExpression *Expr,
324 const DebugLoc &DL,
325 MachineIRBuilder &MIRBuilder);
326
327 bool translateInlineAsm(const CallBase &CB, MachineIRBuilder &MIRBuilder);
328
329 /// Common code for translating normal calls or invokes.
330 bool translateCallBase(const CallBase &CB, MachineIRBuilder &MIRBuilder);
331
332 /// Translate call instruction.
333 /// \pre \p U is a call instruction.
334 bool translateCall(const User &U, MachineIRBuilder &MIRBuilder);
335
336 bool translateIntrinsic(
337 const CallBase &CB, Intrinsic::ID ID, MachineIRBuilder &MIRBuilder,
338 ArrayRef<TargetLowering::IntrinsicInfo> TgtMemIntrinsicInfos = {});
339
340 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
341 /// many places it could ultimately go. In the IR, we have a single unwind
342 /// destination, but in the machine CFG, we enumerate all the possible blocks.
343 /// This function skips over imaginary basic blocks that hold catchswitch
344 /// instructions, and finds all the "real" machine
345 /// basic block destinations. As those destinations may not be successors of
346 /// EHPadBB, here we also calculate the edge probability to those
347 /// destinations. The passed-in Prob is the edge probability to EHPadBB.
348 bool findUnwindDestinations(
349 const BasicBlock *EHPadBB, BranchProbability Prob,
350 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
351 &UnwindDests);
352
353 bool translateInvoke(const User &U, MachineIRBuilder &MIRBuilder);
354
355 bool translateCallBr(const User &U, MachineIRBuilder &MIRBuilder);
356
357 bool translateLandingPad(const User &U, MachineIRBuilder &MIRBuilder);
358
359 /// Translate one of LLVM's cast instructions into MachineInstrs, with the
360 /// given generic Opcode.
361 bool translateCast(unsigned Opcode, const User &U,
362 MachineIRBuilder &MIRBuilder);
363
364 /// Translate a phi instruction.
365 bool translatePHI(const User &U, MachineIRBuilder &MIRBuilder);
366
367 /// Translate a comparison (icmp or fcmp) instruction or constant.
368 bool translateCompare(const User &U, MachineIRBuilder &MIRBuilder);
369
370 /// Translate an integer compare instruction (or constant).
371 bool translateICmp(const User &U, MachineIRBuilder &MIRBuilder) {
372 return translateCompare(U, MIRBuilder);
373 }
374
375 /// Translate a floating-point compare instruction (or constant).
376 bool translateFCmp(const User &U, MachineIRBuilder &MIRBuilder) {
377 return translateCompare(U, MIRBuilder);
378 }
379
380 /// Add remaining operands onto phis we've translated. Executed after all
381 /// MachineBasicBlocks for the function have been created.
382 void finishPendingPhis();
383
384 /// Translate \p Inst into a unary operation \p Opcode.
385 /// \pre \p U is a unary operation.
386 bool translateUnaryOp(unsigned Opcode, const User &U,
387 MachineIRBuilder &MIRBuilder);
388
389 /// Translate \p Inst into a binary operation \p Opcode.
390 /// \pre \p U is a binary operation.
391 bool translateBinaryOp(unsigned Opcode, const User &U,
392 MachineIRBuilder &MIRBuilder);
393
394 /// If the set of cases should be emitted as a series of branches, return
395 /// true. If we should emit this as a bunch of and/or'd together conditions,
396 /// return false.
397 bool shouldEmitAsBranches(const std::vector<SwitchCG::CaseBlock> &Cases);
398 /// Helper method for findMergedConditions.
399 /// This function emits a branch and is used at the leaves of an OR or an
400 /// AND operator tree.
401 void emitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB,
403 MachineBasicBlock *CurBB,
404 MachineBasicBlock *SwitchBB,
405 BranchProbability TProb,
406 BranchProbability FProb, bool InvertCond);
407 /// Used during condbr translation to find trees of conditions that can be
408 /// optimized.
409 void findMergedConditions(const Value *Cond, MachineBasicBlock *TBB,
411 MachineBasicBlock *SwitchBB,
413 BranchProbability FProb, bool InvertCond);
414
415 /// Translate branch (br) instruction.
416 /// \pre \p U is a branch instruction.
417 bool translateUncondBr(const User &U, MachineIRBuilder &MIRBuilder);
418 bool translateCondBr(const User &U, MachineIRBuilder &MIRBuilder);
419
420 // Begin switch lowering functions.
421 bool emitJumpTableHeader(SwitchCG::JumpTable &JT,
423 MachineBasicBlock *HeaderBB);
424 void emitJumpTable(SwitchCG::JumpTable &JT, MachineBasicBlock *MBB);
425
426 void emitSwitchCase(SwitchCG::CaseBlock &CB, MachineBasicBlock *SwitchBB,
427 MachineIRBuilder &MIB);
428
429 /// Generate for the BitTest header block, which precedes each sequence of
430 /// BitTestCases.
431 void emitBitTestHeader(SwitchCG::BitTestBlock &BTB,
432 MachineBasicBlock *SwitchMBB);
433 /// Generate code to produces one "bit test" for a given BitTestCase \p B.
434 void emitBitTestCase(SwitchCG::BitTestBlock &BB, MachineBasicBlock *NextMBB,
435 BranchProbability BranchProbToNext, Register Reg,
437
438 void splitWorkItem(SwitchCG::SwitchWorkList &WorkList,
440 MachineBasicBlock *SwitchMBB, MachineIRBuilder &MIB);
441
442 bool lowerJumpTableWorkItem(
444 MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB,
447 MachineBasicBlock *Fallthrough, bool FallthroughUnreachable);
448
449 bool lowerSwitchRangeWorkItem(SwitchCG::CaseClusterIt I, Value *Cond,
450 MachineBasicBlock *Fallthrough,
451 bool FallthroughUnreachable,
452 BranchProbability UnhandledProbs,
453 MachineBasicBlock *CurMBB,
454 MachineIRBuilder &MIB,
455 MachineBasicBlock *SwitchMBB);
456
457 bool lowerBitTestWorkItem(
459 MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB,
461 BranchProbability DefaultProb, BranchProbability UnhandledProbs,
463 bool FallthroughUnreachable);
464
465 bool lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W, Value *Cond,
466 MachineBasicBlock *SwitchMBB,
467 MachineBasicBlock *DefaultMBB,
468 MachineIRBuilder &MIB);
469
470 bool translateSwitch(const User &U, MachineIRBuilder &MIRBuilder);
471 // End switch lowering section.
472
473 bool translateIndirectBr(const User &U, MachineIRBuilder &MIRBuilder);
474
475 bool translateExtractValue(const User &U, MachineIRBuilder &MIRBuilder);
476
477 bool translateInsertValue(const User &U, MachineIRBuilder &MIRBuilder);
478
479 bool translateSelect(const User &U, MachineIRBuilder &MIRBuilder);
480
481 bool translateGetElementPtr(const User &U, MachineIRBuilder &MIRBuilder);
482
483 bool translateAlloca(const User &U, MachineIRBuilder &MIRBuilder);
484
485 /// Translate return (ret) instruction.
486 /// The target needs to implement CallLowering::lowerReturn for
487 /// this to succeed.
488 /// \pre \p U is a return instruction.
489 bool translateRet(const User &U, MachineIRBuilder &MIRBuilder);
490
491 bool translateFNeg(const User &U, MachineIRBuilder &MIRBuilder);
492
493 bool translateAdd(const User &U, MachineIRBuilder &MIRBuilder) {
494 return translateBinaryOp(TargetOpcode::G_ADD, U, MIRBuilder);
495 }
496 bool translateSub(const User &U, MachineIRBuilder &MIRBuilder) {
497 return translateBinaryOp(TargetOpcode::G_SUB, U, MIRBuilder);
498 }
499 bool translateAnd(const User &U, MachineIRBuilder &MIRBuilder) {
500 return translateBinaryOp(TargetOpcode::G_AND, U, MIRBuilder);
501 }
502 bool translateMul(const User &U, MachineIRBuilder &MIRBuilder) {
503 return translateBinaryOp(TargetOpcode::G_MUL, U, MIRBuilder);
504 }
505 bool translateOr(const User &U, MachineIRBuilder &MIRBuilder) {
506 return translateBinaryOp(TargetOpcode::G_OR, U, MIRBuilder);
507 }
508 bool translateXor(const User &U, MachineIRBuilder &MIRBuilder) {
509 return translateBinaryOp(TargetOpcode::G_XOR, U, MIRBuilder);
510 }
511
512 bool translateUDiv(const User &U, MachineIRBuilder &MIRBuilder) {
513 return translateBinaryOp(TargetOpcode::G_UDIV, U, MIRBuilder);
514 }
515 bool translateSDiv(const User &U, MachineIRBuilder &MIRBuilder) {
516 return translateBinaryOp(TargetOpcode::G_SDIV, U, MIRBuilder);
517 }
518 bool translateURem(const User &U, MachineIRBuilder &MIRBuilder) {
519 return translateBinaryOp(TargetOpcode::G_UREM, U, MIRBuilder);
520 }
521 bool translateSRem(const User &U, MachineIRBuilder &MIRBuilder) {
522 return translateBinaryOp(TargetOpcode::G_SREM, U, MIRBuilder);
523 }
524 bool translateIntToPtr(const User &U, MachineIRBuilder &MIRBuilder) {
525 return translateCast(TargetOpcode::G_INTTOPTR, U, MIRBuilder);
526 }
527 bool translatePtrToInt(const User &U, MachineIRBuilder &MIRBuilder) {
528 return translateCast(TargetOpcode::G_PTRTOINT, U, MIRBuilder);
529 }
530 bool translatePtrToAddr(const User &U, MachineIRBuilder &MIRBuilder) {
531 // FIXME: this is not correct for pointers with addr width != pointer width
532 return translatePtrToInt(U, MIRBuilder);
533 }
534 bool translateTrunc(const User &U, MachineIRBuilder &MIRBuilder) {
535 return translateCast(TargetOpcode::G_TRUNC, U, MIRBuilder);
536 }
537 bool translateFPTrunc(const User &U, MachineIRBuilder &MIRBuilder) {
538 return translateCast(TargetOpcode::G_FPTRUNC, U, MIRBuilder);
539 }
540 bool translateFPExt(const User &U, MachineIRBuilder &MIRBuilder) {
541 return translateCast(TargetOpcode::G_FPEXT, U, MIRBuilder);
542 }
543 bool translateFPToUI(const User &U, MachineIRBuilder &MIRBuilder) {
544 return translateCast(TargetOpcode::G_FPTOUI, U, MIRBuilder);
545 }
546 bool translateFPToSI(const User &U, MachineIRBuilder &MIRBuilder) {
547 return translateCast(TargetOpcode::G_FPTOSI, U, MIRBuilder);
548 }
549 bool translateUIToFP(const User &U, MachineIRBuilder &MIRBuilder) {
550 return translateCast(TargetOpcode::G_UITOFP, U, MIRBuilder);
551 }
552 bool translateSIToFP(const User &U, MachineIRBuilder &MIRBuilder) {
553 return translateCast(TargetOpcode::G_SITOFP, U, MIRBuilder);
554 }
555 bool translateUnreachable(const User &U, MachineIRBuilder &MIRBuilder);
556
557 bool translateSExt(const User &U, MachineIRBuilder &MIRBuilder) {
558 return translateCast(TargetOpcode::G_SEXT, U, MIRBuilder);
559 }
560
561 bool translateZExt(const User &U, MachineIRBuilder &MIRBuilder) {
562 return translateCast(TargetOpcode::G_ZEXT, U, MIRBuilder);
563 }
564
565 bool translateShl(const User &U, MachineIRBuilder &MIRBuilder) {
566 return translateBinaryOp(TargetOpcode::G_SHL, U, MIRBuilder);
567 }
568 bool translateLShr(const User &U, MachineIRBuilder &MIRBuilder) {
569 return translateBinaryOp(TargetOpcode::G_LSHR, U, MIRBuilder);
570 }
571 bool translateAShr(const User &U, MachineIRBuilder &MIRBuilder) {
572 return translateBinaryOp(TargetOpcode::G_ASHR, U, MIRBuilder);
573 }
574
575 bool translateFAdd(const User &U, MachineIRBuilder &MIRBuilder) {
576 return translateBinaryOp(TargetOpcode::G_FADD, U, MIRBuilder);
577 }
578 bool translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
579 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
580 }
581 bool translateFMul(const User &U, MachineIRBuilder &MIRBuilder) {
582 return translateBinaryOp(TargetOpcode::G_FMUL, U, MIRBuilder);
583 }
584 bool translateFDiv(const User &U, MachineIRBuilder &MIRBuilder) {
585 return translateBinaryOp(TargetOpcode::G_FDIV, U, MIRBuilder);
586 }
587 bool translateFRem(const User &U, MachineIRBuilder &MIRBuilder) {
588 return translateBinaryOp(TargetOpcode::G_FREM, U, MIRBuilder);
589 }
590
591 bool translateVAArg(const User &U, MachineIRBuilder &MIRBuilder);
592
593 bool translateInsertElement(const User &U, MachineIRBuilder &MIRBuilder);
594 bool translateInsertVector(const User &U, MachineIRBuilder &MIRBuilder);
595
596 bool translateExtractElement(const User &U, MachineIRBuilder &MIRBuilder);
597 bool translateExtractVector(const User &U, MachineIRBuilder &MIRBuilder);
598
599 bool translateShuffleVector(const User &U, MachineIRBuilder &MIRBuilder);
600
601 bool translateAtomicCmpXchg(const User &U, MachineIRBuilder &MIRBuilder);
602 bool translateAtomicRMW(const User &U, MachineIRBuilder &MIRBuilder);
603 bool translateFence(const User &U, MachineIRBuilder &MIRBuilder);
604 bool translateFreeze(const User &U, MachineIRBuilder &MIRBuilder);
605
606 bool translateBitExtract(const User &U, MachineIRBuilder &MIRBuilder);
607 bool translateBitInsert(const User &U, MachineIRBuilder &MIRBuilder);
608
609 // Stubs to keep the compiler happy while we implement the rest of the
610 // translation.
611 bool translateResume(const User &U, MachineIRBuilder &MIRBuilder) {
612 return false;
613 }
614 bool translateCleanupRet(const User &U, MachineIRBuilder &MIRBuilder) {
615 return false;
616 }
617 bool translateCatchRet(const User &U, MachineIRBuilder &MIRBuilder) {
618 return false;
619 }
620 bool translateCatchSwitch(const User &U, MachineIRBuilder &MIRBuilder) {
621 return false;
622 }
623 bool translateAddrSpaceCast(const User &U, MachineIRBuilder &MIRBuilder) {
624 return translateCast(TargetOpcode::G_ADDRSPACE_CAST, U, MIRBuilder);
625 }
626 bool translateCleanupPad(const User &U, MachineIRBuilder &MIRBuilder) {
627 return false;
628 }
629 bool translateCatchPad(const User &U, MachineIRBuilder &MIRBuilder) {
630 return false;
631 }
632 bool translateUserOp1(const User &U, MachineIRBuilder &MIRBuilder) {
633 return false;
634 }
635 bool translateUserOp2(const User &U, MachineIRBuilder &MIRBuilder) {
636 return false;
637 }
638
639 bool translateConvergenceControlIntrinsic(const CallInst &CI,
640 Intrinsic::ID ID,
641 MachineIRBuilder &MIRBuilder);
642
643 /// @}
644
645 // Builder for machine instruction a la IRBuilder.
646 // I.e., compared to regular MIBuilder, this one also inserts the instruction
647 // in the current block, it can creates block, etc., basically a kind of
648 // IRBuilder, but for Machine IR.
649 // CSEMIRBuilder CurBuilder;
650 std::unique_ptr<MachineIRBuilder> CurBuilder;
651
652 // Builder set to the entry block (just after ABI lowering instructions). Used
653 // as a convenient location for Constants.
654 // CSEMIRBuilder EntryBuilder;
655 std::unique_ptr<MachineIRBuilder> EntryBuilder;
656
657 // The MachineFunction currently being translated.
658 MachineFunction *MF = nullptr;
659
660 /// MachineRegisterInfo used to create virtual registers.
661 MachineRegisterInfo *MRI = nullptr;
662
663 const DataLayout *DL = nullptr;
664
665 CodeGenOptLevel OptLevel;
666
667 /// Current optimization remark emitter. Used to report failures.
668 std::unique_ptr<OptimizationRemarkEmitter> ORE;
669
670 AAResults *AA = nullptr;
671 AssumptionCache *AC = nullptr;
672 const TargetLibraryInfo *LibInfo = nullptr;
673 const LibcallLoweringInfo *Libcalls = nullptr;
674 const TargetLowering *TLI = nullptr;
675 FunctionLoweringInfo FuncInfo;
676
677 // True when either the Target Machine specifies no optimizations or the
678 // function has the optnone attribute.
679 bool EnableOpts = false;
680
681 /// True when the block contains a tail call. This allows the IRTranslator to
682 /// stop translating such blocks early.
683 bool HasTailCall = false;
684
685 StackProtectorDescriptor SPDescriptor;
686
687 bool mayTranslateUserTypes(const User &U) const;
688
689 /// Switch analysis and optimization.
690 class GISelSwitchLowering : public SwitchCG::SwitchLowering {
691 public:
692 GISelSwitchLowering(IRTranslatorImpl *irt, FunctionLoweringInfo &funcinfo)
693 : SwitchLowering(funcinfo), IRT(irt) {
694 assert(irt && "irt is null!");
695 }
696
697 void addSuccessorWithProb(
700 IRT->addSuccessorWithProb(Src, Dst, Prob);
701 }
702
703 ~GISelSwitchLowering() override = default;
704
705 private:
706 IRTranslatorImpl *IRT;
707 };
708
709 std::unique_ptr<GISelSwitchLowering> SL;
710
711 // * Insert all the code needed to materialize the constants
712 // at the proper place. E.g., Entry block or dominator block
713 // of each constant depending on how fancy we want to be.
714 // * Clear the different maps.
715 void finalizeFunction();
716
717 // Processing steps done per block. E.g. emitting jump tables, stack
718 // protectors etc. Returns true if no errors, false if there was a problem
719 // that caused an abort.
720 bool finalizeBasicBlock(const BasicBlock &BB, MachineBasicBlock &MBB);
721
722 /// Codegen a new tail for a stack protector check ParentMBB which has had its
723 /// tail spliced into a stack protector check success bb.
724 ///
725 /// For a high level explanation of how this fits into the stack protector
726 /// generation see the comment on the declaration of class
727 /// StackProtectorDescriptor.
728 ///
729 /// \return true if there were no problems.
730 bool emitSPDescriptorParent(StackProtectorDescriptor &SPD,
731 MachineBasicBlock *ParentBB);
732
733 /// Codegen the failure basic block for a stack protector check.
734 ///
735 /// A failure stack protector machine basic block consists simply of a call to
736 /// __stack_chk_fail().
737 ///
738 /// For a high level explanation of how this fits into the stack protector
739 /// generation see the comment on the declaration of class
740 /// StackProtectorDescriptor.
741 ///
742 /// \return true if there were no problems.
743 bool emitSPDescriptorFailure(StackProtectorDescriptor &SPD,
744 MachineBasicBlock *FailureBB);
745
746 /// Get the VRegs that represent \p Val.
747 /// Non-aggregate types have just one corresponding VReg and the list can be
748 /// used as a single "unsigned". Aggregates get flattened. If such VRegs do
749 /// not exist, they are created.
750 ArrayRef<Register> getOrCreateVRegs(const Value &Val);
751
752 Register getOrCreateVReg(const Value &Val) {
753 auto Regs = getOrCreateVRegs(Val);
754 if (Regs.empty())
755 return 0;
756 assert(Regs.size() == 1 &&
757 "attempt to get single VReg for aggregate or void");
758 return Regs[0];
759 }
760
761 Register getOrCreateConvergenceTokenVReg(const Value &Token) {
762 assert(Token.getType()->isTokenTy());
763 auto &Regs = *VMap.getVRegs(Token);
764 if (!Regs.empty()) {
765 assert(Regs.size() == 1 &&
766 "Expected a single register for convergence tokens.");
767 return Regs[0];
768 }
769
770 auto Reg = MRI->createGenericVirtualRegister(LLT::token());
771 Regs.push_back(Reg);
772 return Reg;
773 }
774
775 /// Allocate empty vregs for \p Val. For aggregate values, also populate
776 /// their offsets.
777 ValueToVRegInfo::VRegListT &allocateVRegs(const Value &Val);
778
779 /// Get the frame index that represents \p Val.
780 /// If such VReg does not exist, it is created.
781 int getOrCreateFrameIndex(const AllocaInst &AI);
782
783 /// Get the alignment of the given memory operation instruction. This will
784 /// either be the explicitly specified value or the ABI-required alignment for
785 /// the type being accessed (according to the Module's DataLayout).
786 Align getMemOpAlign(const Instruction &I);
787
788 /// Get the MachineBasicBlock that represents \p BB. Specifically, the block
789 /// returned will be the head of the translated block (suitable for branch
790 /// destinations).
791 MachineBasicBlock &getMBB(const BasicBlock &BB);
792
793 /// Record \p NewPred as a Machine predecessor to `Edge.second`, corresponding
794 /// to `Edge.first` at the IR level. This is used when IRTranslation creates
795 /// multiple MachineBasicBlocks for a given IR block and the CFG is no longer
796 /// represented simply by the IR-level CFG.
797 void addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred);
798
799 /// Returns the Machine IR predecessors for the given IR CFG edge. Usually
800 /// this is just the single MachineBasicBlock corresponding to the predecessor
801 /// in the IR. More complex lowering can result in multiple MachineBasicBlocks
802 /// preceding the original though (e.g. switch instructions).
803 SmallVector<MachineBasicBlock *, 1> getMachinePredBBs(CFGEdge Edge) {
804 auto RemappedEdge = MachinePreds.find(Edge);
805 if (RemappedEdge != MachinePreds.end())
806 return RemappedEdge->second;
807 return SmallVector<MachineBasicBlock *, 4>(1, &getMBB(*Edge.first));
808 }
809
810 /// Return branch probability calculated by BranchProbabilityInfo for IR
811 /// blocks.
812 BranchProbability getEdgeProbability(const MachineBasicBlock *Src,
813 const MachineBasicBlock *Dst) const;
814
815 void addSuccessorWithProb(
818
819public:
821 : OptLevel(OptLevel) {}
822
823 // Algo:
824 // CallLowering = MF.subtarget.getCallLowering()
825 // F = MF.getParent()
826 // MIRBuilder.reset(MF)
827 // getMBB(F.getEntryBB())
828 // CallLowering->translateArguments(MIRBuilder, F, ValToVReg)
829 // for each bb in F
830 // getMBB(bb)
831 // for each inst in bb
832 // if (!translate(MIRBuilder, inst, ValToVReg, ConstantToSequence))
833 // reportFatalUsageError("Don't know how to translate input");
834 // finalize()
836 function_ref<GISelCSEInfo *()> GetCSEInfo,
837 bool ShouldSkipOpts,
838 function_ref<AAResults *()> GetAAResults,
840 function_ref<AssumptionCache *()> GetAC,
841 TargetLibraryInfo *LibraryInfo,
842 const LibcallLoweringInfo *LibcallInfo,
843 SSPLayoutInfo *StackProtectorInfo);
844};
845
846} // namespace llvm
847
849
851 "IRTranslator LLVM IR -> MI", false, false)
858 "IRTranslator LLVM IR -> MI", false, false)
859
863 MF.getProperties().setFailedISel();
864 bool IsGlobalISelAbortEnabled =
865 MF.getTarget().Options.GlobalISelAbort == GlobalISelAbortMode::Enable;
866
867 // Print the function name explicitly if we don't have a debug location (which
868 // makes the diagnostic less useful) or if we're going to emit a raw error.
869 if (!R.getLocation().isValid() || IsGlobalISelAbortEnabled)
870 R << (" (in function: " + MF.getName() + ")").str();
871
872 if (IsGlobalISelAbortEnabled)
873 report_fatal_error(Twine(R.getMsg()));
874 else
875 ORE.emit(R);
876}
877
879 : MachineFunctionPass(ID), OptLevel(OptLevel),
880 Impl(std::make_unique<IRTranslatorImpl>(OptLevel)) {}
881
883
884#ifndef NDEBUG
885namespace {
886/// Verify that every instruction created has the same DILocation as the
887/// instruction being translated.
888class DILocationVerifier : public GISelChangeObserver {
889 const Instruction *CurrInst = nullptr;
890
891public:
892 DILocationVerifier() = default;
893 ~DILocationVerifier() override = default;
894
895 const Instruction *getCurrentInst() const { return CurrInst; }
896 void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; }
897
898 void erasingInstr(MachineInstr &MI) override {}
899 void changingInstr(MachineInstr &MI) override {}
900 void changedInstr(MachineInstr &MI) override {}
901
902 void createdInstr(MachineInstr &MI) override {
903 assert(getCurrentInst() && "Inserted instruction without a current MI");
904
905 // Only print the check message if we're actually checking it.
906#ifndef NDEBUG
907 LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst
908 << " was copied to " << MI);
909#endif
910 // We allow insts in the entry block to have no debug loc because
911 // they could have originated from constants, and we don't want a jumpy
912 // debug experience.
913 assert((CurrInst->getDebugLoc() == MI.getDebugLoc() ||
914 (MI.getParent()->isEntryBlock() && !MI.getDebugLoc()) ||
915 (MI.isDebugInstr())) &&
916 "Line info was not transferred to all instructions");
917 }
918};
919} // namespace
920#endif // ifndef NDEBUG
921
938
939IRTranslatorImpl::ValueToVRegInfo::VRegListT &
940IRTranslatorImpl::allocateVRegs(const Value &Val) {
941 auto VRegsIt = VMap.findVRegs(Val);
942 if (VRegsIt != VMap.vregs_end())
943 return *VRegsIt->second;
944 auto *Regs = VMap.getVRegs(Val);
945 if (!Val.getType()->isAggregateType()) {
946 Regs->push_back(0);
947 return *Regs;
948 }
949
950 auto *Offsets = VMap.getOffsets(Val);
951 SmallVector<LLT, 4> SplitTys;
952 computeValueLLTs(*DL, *Val.getType(), SplitTys,
953 Offsets->empty() ? Offsets : nullptr);
954 for (unsigned i = 0; i < SplitTys.size(); ++i)
955 Regs->push_back(0);
956 return *Regs;
957}
958
959ArrayRef<Register> IRTranslatorImpl::getOrCreateVRegs(const Value &Val) {
960 auto VRegsIt = VMap.findVRegs(Val);
961 if (VRegsIt != VMap.vregs_end())
962 return *VRegsIt->second;
963
964 if (Val.getType()->isVoidTy())
965 return *VMap.getVRegs(Val);
966
967 // Create entry for this type.
968 auto *VRegs = VMap.getVRegs(Val);
969
970 if (!Val.getType()->isTokenTy())
971 assert(Val.getType()->isSized() &&
972 "Don't know how to create an empty vreg");
973
974 // Fast-path values that lower to a single vreg.
975 if (!Val.getType()->isAggregateType()) {
976 LLT Ty = getLLTForType(*Val.getType(), *DL);
977 VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
978 if (isa<Constant>(Val)) {
979 bool Success = translate(cast<Constant>(Val), VRegs->front());
980 if (!Success) {
981 OptimizationRemarkMissed R("gisel-ir-translator", "GISelFailure",
982 MF->getFunction().getSubprogram(),
983 &MF->getFunction().getEntryBlock());
984 R << "unable to translate constant: " << ore::NV("Type", Val.getType());
985 reportTranslationError(*MF, *ORE, R);
986 }
987 }
988 return *VRegs;
989 }
990
991 SmallVector<LLT, 4> SplitTys;
992 auto *Offsets = VMap.getOffsets(Val);
993 computeValueLLTs(*DL, *Val.getType(), SplitTys,
994 Offsets->empty() ? Offsets : nullptr);
995
996 if (!isa<Constant>(Val)) {
997 for (auto Ty : SplitTys)
998 VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
999 return *VRegs;
1000 }
1001
1002 // UndefValue, ConstantAggregateZero
1003 auto &C = cast<Constant>(Val);
1004 unsigned Idx = 0;
1005 while (auto Elt = C.getAggregateElement(Idx++)) {
1006 auto EltRegs = getOrCreateVRegs(*Elt);
1007 llvm::append_range(*VRegs, EltRegs);
1008 }
1009
1010 return *VRegs;
1011}
1012
1013int IRTranslatorImpl::getOrCreateFrameIndex(const AllocaInst &AI) {
1014 auto [MapEntry, Inserted] = FrameIndices.try_emplace(&AI);
1015 if (!Inserted)
1016 return MapEntry->second;
1017
1018 TypeSize TySize = AI.getAllocationSize(*DL).value_or(TypeSize::getZero());
1019 uint64_t Size = TySize.getKnownMinValue();
1020
1021 // Always allocate at least one byte.
1022 Size = std::max<uint64_t>(Size, 1u);
1023
1024 int &FI = MapEntry->second;
1025 FI = MF->getFrameInfo().CreateStackObject(Size, AI.getAlign(), false, &AI);
1026
1027 // Scalable vectors and structures that contain scalable vectors may
1028 // need a special StackID to distinguish them from other (fixed size)
1029 // stack objects.
1030 if (TySize.isScalable()) {
1031 auto StackID =
1032 MF->getSubtarget().getFrameLowering()->getStackIDForScalableVectors();
1033 MF->getFrameInfo().setStackID(FI, StackID);
1034 }
1035
1036 return FI;
1037}
1038
1039Align IRTranslatorImpl::getMemOpAlign(const Instruction &I) {
1040 if (const StoreInst *SI = dyn_cast<StoreInst>(&I))
1041 return SI->getAlign();
1042 if (const LoadInst *LI = dyn_cast<LoadInst>(&I))
1043 return LI->getAlign();
1044 if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I))
1045 return AI->getAlign();
1046 if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I))
1047 return AI->getAlign();
1048
1049 OptimizationRemarkMissed R("gisel-ir-translator", "", &I);
1050 R << "unable to translate memop: " << ore::NV("Opcode", &I);
1051 reportTranslationError(*MF, *ORE, R);
1052 return Align(1);
1053}
1054
1055MachineBasicBlock &IRTranslatorImpl::getMBB(const BasicBlock &BB) {
1056 MachineBasicBlock *MBB = FuncInfo.getMBB(&BB);
1057 assert(MBB && "BasicBlock was not encountered before");
1058 return *MBB;
1059}
1060
1061void IRTranslatorImpl::addMachineCFGPred(CFGEdge Edge,
1062 MachineBasicBlock *NewPred) {
1063 assert(NewPred && "new predecessor must be a real MachineBasicBlock");
1064 MachinePreds[Edge].push_back(NewPred);
1065}
1066
1067bool IRTranslatorImpl::translateBinaryOp(unsigned Opcode, const User &U,
1068 MachineIRBuilder &MIRBuilder) {
1069 if (!mayTranslateUserTypes(U))
1070 return false;
1071
1072 // Get or create a virtual register for each value.
1073 // Unless the value is a Constant => loadimm cst?
1074 // or inline constant each time?
1075 // Creation of a virtual register needs to have a size.
1076 Register Op0 = getOrCreateVReg(*U.getOperand(0));
1077 Register Op1 = getOrCreateVReg(*U.getOperand(1));
1078 Register Res = getOrCreateVReg(U);
1079 uint32_t Flags = 0;
1080 if (isa<Instruction>(U)) {
1081 const Instruction &I = cast<Instruction>(U);
1083 }
1084
1085 MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags);
1086 return true;
1087}
1088
1089bool IRTranslatorImpl::translateUnaryOp(unsigned Opcode, const User &U,
1090 MachineIRBuilder &MIRBuilder) {
1091 if (!mayTranslateUserTypes(U))
1092 return false;
1093
1094 Register Op0 = getOrCreateVReg(*U.getOperand(0));
1095 Register Res = getOrCreateVReg(U);
1096 uint32_t Flags = 0;
1097 if (isa<Instruction>(U)) {
1098 const Instruction &I = cast<Instruction>(U);
1100 }
1101 MIRBuilder.buildInstr(Opcode, {Res}, {Op0}, Flags);
1102 return true;
1103}
1104
1105bool IRTranslatorImpl::translateFNeg(const User &U,
1106 MachineIRBuilder &MIRBuilder) {
1107 return translateUnaryOp(TargetOpcode::G_FNEG, U, MIRBuilder);
1108}
1109
1110bool IRTranslatorImpl::translateCompare(const User &U,
1111 MachineIRBuilder &MIRBuilder) {
1112 if (!mayTranslateUserTypes(U))
1113 return false;
1114
1115 auto *CI = cast<CmpInst>(&U);
1116 Register Op0 = getOrCreateVReg(*U.getOperand(0));
1117 Register Op1 = getOrCreateVReg(*U.getOperand(1));
1118 Register Res = getOrCreateVReg(U);
1119 CmpInst::Predicate Pred = CI->getPredicate();
1121 if (CmpInst::isIntPredicate(Pred))
1122 MIRBuilder.buildICmp(Pred, Res, Op0, Op1, Flags);
1123 else if (Pred == CmpInst::FCMP_FALSE)
1124 MIRBuilder.buildCopy(
1125 Res, getOrCreateVReg(*Constant::getNullValue(U.getType())));
1126 else if (Pred == CmpInst::FCMP_TRUE)
1127 MIRBuilder.buildCopy(
1128 Res, getOrCreateVReg(*Constant::getAllOnesValue(U.getType())));
1129 else
1130 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1, Flags);
1131
1132 return true;
1133}
1134
1135bool IRTranslatorImpl::translateRet(const User &U,
1136 MachineIRBuilder &MIRBuilder) {
1137 const ReturnInst &RI = cast<ReturnInst>(U);
1138 const Value *Ret = RI.getReturnValue();
1139 if (Ret && DL->getTypeStoreSize(Ret->getType()).isZero())
1140 Ret = nullptr;
1141
1142 ArrayRef<Register> VRegs;
1143 if (Ret)
1144 VRegs = getOrCreateVRegs(*Ret);
1145
1146 Register SwiftErrorVReg = 0;
1147 if (CLI->supportSwiftError() && SwiftError.getFunctionArg()) {
1148 SwiftErrorVReg = SwiftError.getOrCreateVRegUseAt(
1149 &RI, &MIRBuilder.getMBB(), SwiftError.getFunctionArg());
1150 }
1151
1152 // The target may mess up with the insertion point, but
1153 // this is not important as a return is the last instruction
1154 // of the block anyway.
1155 return CLI->lowerReturn(MIRBuilder, Ret, VRegs, FuncInfo, SwiftErrorVReg);
1156}
1157
1158void IRTranslatorImpl::emitBranchForMergedCondition(
1160 MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB,
1161 BranchProbability TProb, BranchProbability FProb, bool InvertCond) {
1162 // If the leaf of the tree is a comparison, merge the condition into
1163 // the caseblock.
1164 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1165 CmpInst::Predicate Condition;
1166 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1167 Condition = InvertCond ? IC->getInversePredicate() : IC->getPredicate();
1168 } else {
1169 const FCmpInst *FC = cast<FCmpInst>(Cond);
1170 Condition = InvertCond ? FC->getInversePredicate() : FC->getPredicate();
1171 }
1172
1173 SwitchCG::CaseBlock CB(Condition, false, BOp->getOperand(0),
1174 BOp->getOperand(1), nullptr, TBB, FBB, CurBB,
1175 CurBuilder->getDebugLoc(), TProb, FProb);
1176 SL->SwitchCases.push_back(CB);
1177 return;
1178 }
1179
1180 // Create a CaseBlock record representing this branch.
1182 SwitchCG::CaseBlock CB(
1183 Pred, false, Cond, ConstantInt::getTrue(MF->getFunction().getContext()),
1184 nullptr, TBB, FBB, CurBB, CurBuilder->getDebugLoc(), TProb, FProb);
1185 SL->SwitchCases.push_back(CB);
1186}
1187
1188static bool isValInBlock(const Value *V, const BasicBlock *BB) {
1189 if (const Instruction *I = dyn_cast<Instruction>(V))
1190 return I->getParent() == BB;
1191 return true;
1192}
1193
1194void IRTranslatorImpl::findMergedConditions(
1196 MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB,
1198 BranchProbability FProb, bool InvertCond) {
1199 using namespace PatternMatch;
1200 assert((Opc == Instruction::And || Opc == Instruction::Or) &&
1201 "Expected Opc to be AND/OR");
1202 // Skip over not part of the tree and remember to invert op and operands at
1203 // next level.
1204 Value *NotCond;
1205 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
1206 isValInBlock(NotCond, CurBB->getBasicBlock())) {
1207 findMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
1208 !InvertCond);
1209 return;
1210 }
1211
1213 const Value *BOpOp0, *BOpOp1;
1214 // Compute the effective opcode for Cond, taking into account whether it needs
1215 // to be inverted, e.g.
1216 // and (not (or A, B)), C
1217 // gets lowered as
1218 // and (and (not A, not B), C)
1220 if (BOp) {
1221 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
1222 ? Instruction::And
1223 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
1224 ? Instruction::Or
1226 if (InvertCond) {
1227 if (BOpc == Instruction::And)
1228 BOpc = Instruction::Or;
1229 else if (BOpc == Instruction::Or)
1230 BOpc = Instruction::And;
1231 }
1232 }
1233
1234 // If this node is not part of the or/and tree, emit it as a branch.
1235 // Note that all nodes in the tree should have same opcode.
1236 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
1237 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
1238 !isValInBlock(BOpOp0, CurBB->getBasicBlock()) ||
1239 !isValInBlock(BOpOp1, CurBB->getBasicBlock())) {
1240 emitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, TProb, FProb,
1241 InvertCond);
1242 return;
1243 }
1244
1245 // Create TmpBB after CurBB.
1246 MachineFunction::iterator BBI(CurBB);
1247 MachineBasicBlock *TmpBB =
1248 MF->CreateMachineBasicBlock(CurBB->getBasicBlock());
1249 CurBB->getParent()->insert(++BBI, TmpBB);
1250
1251 if (Opc == Instruction::Or) {
1252 // Codegen X | Y as:
1253 // BB1:
1254 // jmp_if_X TBB
1255 // jmp TmpBB
1256 // TmpBB:
1257 // jmp_if_Y TBB
1258 // jmp FBB
1259 //
1260
1261 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1262 // The requirement is that
1263 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1264 // = TrueProb for original BB.
1265 // Assuming the original probabilities are A and B, one choice is to set
1266 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1267 // A/(1+B) and 2B/(1+B). This choice assumes that
1268 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1269 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1270 // TmpBB, but the math is more complicated.
1271
1272 auto NewTrueProb = TProb / 2;
1273 auto NewFalseProb = TProb / 2 + FProb;
1274 // Emit the LHS condition.
1275 findMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
1276 NewFalseProb, InvertCond);
1277
1278 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1279 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1281 // Emit the RHS condition into TmpBB.
1282 findMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
1283 Probs[1], InvertCond);
1284 } else {
1285 assert(Opc == Instruction::And && "Unknown merge op!");
1286 // Codegen X & Y as:
1287 // BB1:
1288 // jmp_if_X TmpBB
1289 // jmp FBB
1290 // TmpBB:
1291 // jmp_if_Y TBB
1292 // jmp FBB
1293 //
1294 // This requires creation of TmpBB after CurBB.
1295
1296 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1297 // The requirement is that
1298 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1299 // = FalseProb for original BB.
1300 // Assuming the original probabilities are A and B, one choice is to set
1301 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1302 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1303 // TrueProb for BB1 * FalseProb for TmpBB.
1304
1305 auto NewTrueProb = TProb + FProb / 2;
1306 auto NewFalseProb = FProb / 2;
1307 // Emit the LHS condition.
1308 findMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
1309 NewFalseProb, InvertCond);
1310
1311 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1312 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1314 // Emit the RHS condition into TmpBB.
1315 findMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
1316 Probs[1], InvertCond);
1317 }
1318}
1319
1320bool IRTranslatorImpl::shouldEmitAsBranches(
1321 const std::vector<SwitchCG::CaseBlock> &Cases) {
1322 // For multiple cases, it's better to emit as branches.
1323 if (Cases.size() != 2)
1324 return true;
1325
1326 // If this is two comparisons of the same values or'd or and'd together, they
1327 // will get folded into a single comparison, so don't emit two blocks.
1328 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1329 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1330 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1331 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1332 return false;
1333 }
1334
1335 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1336 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1337 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1338 Cases[0].PredInfo.Pred == Cases[1].PredInfo.Pred &&
1339 isa<Constant>(Cases[0].CmpRHS) &&
1340 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1341 if (Cases[0].PredInfo.Pred == CmpInst::ICMP_EQ &&
1342 Cases[0].TrueBB == Cases[1].ThisBB)
1343 return false;
1344 if (Cases[0].PredInfo.Pred == CmpInst::ICMP_NE &&
1345 Cases[0].FalseBB == Cases[1].ThisBB)
1346 return false;
1347 }
1348
1349 return true;
1350}
1351
1352bool IRTranslatorImpl::translateUncondBr(const User &U,
1353 MachineIRBuilder &MIRBuilder) {
1354 const UncondBrInst &BrInst = cast<UncondBrInst>(U);
1355 auto &CurMBB = MIRBuilder.getMBB();
1356 auto *Succ0MBB = &getMBB(*BrInst.getSuccessor(0));
1357
1358 // If the unconditional target is the layout successor, fallthrough.
1359 if (OptLevel == CodeGenOptLevel::None || !CurMBB.isLayoutSuccessor(Succ0MBB))
1360 MIRBuilder.buildBr(*Succ0MBB);
1361
1362 // Link successors.
1363 for (const BasicBlock *Succ : successors(&BrInst))
1364 CurMBB.addSuccessor(&getMBB(*Succ));
1365 return true;
1366}
1367
1368bool IRTranslatorImpl::translateCondBr(const User &U,
1369 MachineIRBuilder &MIRBuilder) {
1370 const CondBrInst &BrInst = cast<CondBrInst>(U);
1371 auto &CurMBB = MIRBuilder.getMBB();
1372 auto *Succ0MBB = &getMBB(*BrInst.getSuccessor(0));
1373
1374 // If this condition is one of the special cases we handle, do special stuff
1375 // now.
1376 const Value *CondVal = BrInst.getCondition();
1377 MachineBasicBlock *Succ1MBB = &getMBB(*BrInst.getSuccessor(1));
1378
1379 // If this is a series of conditions that are or'd or and'd together, emit
1380 // this as a sequence of branches instead of setcc's with and/or operations.
1381 // As long as jumps are not expensive (exceptions for multi-use logic ops,
1382 // unpredictable branches, and vector extracts because those jumps are likely
1383 // expensive for any target), this should improve performance.
1384 // For example, instead of something like:
1385 // cmp A, B
1386 // C = seteq
1387 // cmp D, E
1388 // F = setle
1389 // or C, F
1390 // jnz foo
1391 // Emit:
1392 // cmp A, B
1393 // je foo
1394 // cmp D, E
1395 // jle foo
1396 using namespace PatternMatch;
1397 const Instruction *CondI = dyn_cast<Instruction>(CondVal);
1398 if (!TLI->isJumpExpensive() && CondI && CondI->hasOneUse() &&
1399 !BrInst.hasMetadata(LLVMContext::MD_unpredictable)) {
1401 Value *Vec;
1402 const Value *BOp0, *BOp1;
1403 if (match(CondI, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
1404 Opcode = Instruction::And;
1405 else if (match(CondI, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
1406 Opcode = Instruction::Or;
1407
1408 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
1409 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
1410 findMergedConditions(CondI, Succ0MBB, Succ1MBB, &CurMBB, &CurMBB, Opcode,
1411 getEdgeProbability(&CurMBB, Succ0MBB),
1412 getEdgeProbability(&CurMBB, Succ1MBB),
1413 /*InvertCond=*/false);
1414 assert(SL->SwitchCases[0].ThisBB == &CurMBB && "Unexpected lowering!");
1415
1416 // Allow some cases to be rejected.
1417 if (shouldEmitAsBranches(SL->SwitchCases)) {
1418 // Emit the branch for this block.
1419 emitSwitchCase(SL->SwitchCases[0], &CurMBB, *CurBuilder);
1420 SL->SwitchCases.erase(SL->SwitchCases.begin());
1421 return true;
1422 }
1423
1424 // Okay, we decided not to do this, remove any inserted MBB's and clear
1425 // SwitchCases.
1426 for (unsigned I = 1, E = SL->SwitchCases.size(); I != E; ++I)
1427 MF->erase(SL->SwitchCases[I].ThisBB);
1428
1429 SL->SwitchCases.clear();
1430 }
1431 }
1432
1433 // Create a CaseBlock record representing this branch.
1434 SwitchCG::CaseBlock CB(CmpInst::ICMP_EQ, false, CondVal,
1435 ConstantInt::getTrue(MF->getFunction().getContext()),
1436 nullptr, Succ0MBB, Succ1MBB, &CurMBB,
1437 CurBuilder->getDebugLoc());
1438
1439 // Use emitSwitchCase to actually insert the fast branch sequence for this
1440 // cond branch.
1441 emitSwitchCase(CB, &CurMBB, *CurBuilder);
1442 return true;
1443}
1444
1445void IRTranslatorImpl::addSuccessorWithProb(MachineBasicBlock *Src,
1446 MachineBasicBlock *Dst,
1447 BranchProbability Prob) {
1448 if (!FuncInfo.BPI) {
1449 Src->addSuccessorWithoutProb(Dst);
1450 return;
1451 }
1452 if (Prob.isUnknown())
1453 Prob = getEdgeProbability(Src, Dst);
1454 Src->addSuccessor(Dst, Prob);
1455}
1456
1458IRTranslatorImpl::getEdgeProbability(const MachineBasicBlock *Src,
1459 const MachineBasicBlock *Dst) const {
1460 const BasicBlock *SrcBB = Src->getBasicBlock();
1461 const BasicBlock *DstBB = Dst->getBasicBlock();
1462 if (!FuncInfo.BPI) {
1463 // If BPI is not available, set the default probability as 1 / N, where N is
1464 // the number of successors.
1465 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1466 return BranchProbability(1, SuccSize);
1467 }
1468 return FuncInfo.BPI->getEdgeProbability(SrcBB, DstBB);
1469}
1470
1471bool IRTranslatorImpl::translateSwitch(const User &U, MachineIRBuilder &MIB) {
1472 using namespace SwitchCG;
1473 // Extract cases from the switch.
1474 const SwitchInst &SI = cast<SwitchInst>(U);
1475 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1476 CaseClusterVector Clusters;
1477 Clusters.reserve(SI.getNumCases());
1478 for (const auto &I : SI.cases()) {
1479 MachineBasicBlock *Succ = &getMBB(*I.getCaseSuccessor());
1480 assert(Succ && "Could not find successor mbb in mapping");
1481 const ConstantInt *CaseVal = I.getCaseValue();
1482 BranchProbability Prob =
1483 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
1484 : BranchProbability(1, SI.getNumCases() + 1);
1485 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
1486 }
1487
1488 MachineBasicBlock *DefaultMBB = &getMBB(*SI.getDefaultDest());
1489
1490 // Cluster adjacent cases with the same destination. We do this at all
1491 // optimization levels because it's cheap to do and will make codegen faster
1492 // if there are many clusters.
1493 sortAndRangeify(Clusters);
1494
1495 MachineBasicBlock *SwitchMBB = &getMBB(*SI.getParent());
1496
1497 // If there is only the default destination, jump there directly.
1498 if (Clusters.empty()) {
1499 SwitchMBB->addSuccessor(DefaultMBB);
1500 if (DefaultMBB != SwitchMBB->getNextNode())
1501 MIB.buildBr(*DefaultMBB);
1502 return true;
1503 }
1504
1505 SL->findJumpTables(Clusters, &SI, std::nullopt, DefaultMBB, nullptr, nullptr);
1506 SL->findBitTestClusters(Clusters, &SI);
1507
1508 LLVM_DEBUG({
1509 dbgs() << "Case clusters: ";
1510 for (const CaseCluster &C : Clusters) {
1511 if (C.Kind == CC_JumpTable)
1512 dbgs() << "JT:";
1513 if (C.Kind == CC_BitTests)
1514 dbgs() << "BT:";
1515
1516 C.Low->getValue().print(dbgs(), true);
1517 if (C.Low != C.High) {
1518 dbgs() << '-';
1519 C.High->getValue().print(dbgs(), true);
1520 }
1521 dbgs() << ' ';
1522 }
1523 dbgs() << '\n';
1524 });
1525
1526 assert(!Clusters.empty());
1527 SwitchWorkList WorkList;
1528 CaseClusterIt First = Clusters.begin();
1529 CaseClusterIt Last = Clusters.end() - 1;
1530 auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
1531 WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
1532
1533 while (!WorkList.empty()) {
1534 SwitchWorkListItem W = WorkList.pop_back_val();
1535
1536 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
1537 // For optimized builds, lower large range as a balanced binary tree.
1538 if (NumClusters > 3 &&
1539 MF->getTarget().getOptLevel() != CodeGenOptLevel::None &&
1540 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
1541 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB, MIB);
1542 continue;
1543 }
1544
1545 if (!lowerSwitchWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB, MIB))
1546 return false;
1547 }
1548 return true;
1549}
1550
1551void IRTranslatorImpl::splitWorkItem(SwitchCG::SwitchWorkList &WorkList,
1553 Value *Cond, MachineBasicBlock *SwitchMBB,
1554 MachineIRBuilder &MIB) {
1555 using namespace SwitchCG;
1556 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
1557 "Clusters not sorted?");
1558 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
1559
1560 auto [LastLeft, FirstRight, LeftProb, RightProb] =
1561 SL->computeSplitWorkItemInfo(W);
1562
1563 // Use the first element on the right as pivot since we will make less-than
1564 // comparisons against it.
1565 CaseClusterIt PivotCluster = FirstRight;
1566 assert(PivotCluster > W.FirstCluster);
1567 assert(PivotCluster <= W.LastCluster);
1568
1569 CaseClusterIt FirstLeft = W.FirstCluster;
1570 CaseClusterIt LastRight = W.LastCluster;
1571
1572 const ConstantInt *Pivot = PivotCluster->Low;
1573
1574 // New blocks will be inserted immediately after the current one.
1576 ++BBI;
1577
1578 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
1579 // we can branch to its destination directly if it's squeezed exactly in
1580 // between the known lower bound and Pivot - 1.
1581 MachineBasicBlock *LeftMBB;
1582 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
1583 FirstLeft->Low == W.GE &&
1584 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
1585 LeftMBB = FirstLeft->MBB;
1586 } else {
1587 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
1588 FuncInfo.MF->insert(BBI, LeftMBB);
1589 WorkList.push_back(
1590 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
1591 }
1592
1593 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
1594 // single cluster, RHS.Low == Pivot, and we can branch to its destination
1595 // directly if RHS.High equals the current upper bound.
1596 MachineBasicBlock *RightMBB;
1597 if (FirstRight == LastRight && FirstRight->Kind == CC_Range && W.LT &&
1598 (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
1599 RightMBB = FirstRight->MBB;
1600 } else {
1601 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
1602 FuncInfo.MF->insert(BBI, RightMBB);
1603 WorkList.push_back(
1604 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
1605 }
1606
1607 // Create the CaseBlock record that will be used to lower the branch.
1608 CaseBlock CB(ICmpInst::Predicate::ICMP_SLT, false, Cond, Pivot, nullptr,
1609 LeftMBB, RightMBB, W.MBB, MIB.getDebugLoc(), LeftProb,
1610 RightProb);
1611
1612 if (W.MBB == SwitchMBB)
1613 emitSwitchCase(CB, SwitchMBB, MIB);
1614 else
1615 SL->SwitchCases.push_back(CB);
1616}
1617
1618void IRTranslatorImpl::emitJumpTable(SwitchCG::JumpTable &JT,
1620 // Emit the code for the jump table
1621 assert(JT.Reg && "Should lower JT Header first!");
1622 MachineIRBuilder MIB(*MBB->getParent());
1623 MIB.setMBB(*MBB);
1624 MIB.setDebugLoc(CurBuilder->getDebugLoc());
1625
1626 Type *PtrIRTy = PointerType::getUnqual(MF->getFunction().getContext());
1627 const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
1628
1629 auto Table = MIB.buildJumpTable(PtrTy, JT.JTI);
1630 MIB.buildBrJT(Table.getReg(0), JT.JTI, JT.Reg);
1631}
1632
1633bool IRTranslatorImpl::emitJumpTableHeader(SwitchCG::JumpTable &JT,
1635 MachineBasicBlock *HeaderBB) {
1636 MachineIRBuilder MIB(*HeaderBB->getParent());
1637 MIB.setMBB(*HeaderBB);
1638 MIB.setDebugLoc(CurBuilder->getDebugLoc());
1639
1640 const Value &SValue = *JTH.SValue;
1641 // Subtract the lowest switch case value from the value being switched on.
1642 const LLT SwitchTy = getLLTForType(*SValue.getType(), *DL);
1643 Register SwitchOpReg = getOrCreateVReg(SValue);
1644 auto FirstCst = MIB.buildConstant(SwitchTy, JTH.First);
1645 auto Sub = MIB.buildSub({SwitchTy}, SwitchOpReg, FirstCst);
1646
1647 // This value may be smaller or larger than the target's pointer type, and
1648 // therefore require extension or truncating.
1649 auto *PtrIRTy = PointerType::getUnqual(SValue.getContext());
1650 const LLT PtrScalarTy = LLT::integer(DL->getTypeSizeInBits(PtrIRTy));
1651 auto Index = MIB.buildZExtOrTrunc(PtrScalarTy, Sub);
1652
1653 JT.Reg = Index.getReg(0);
1654
1655 if (JTH.FallthroughUnreachable) {
1656 if (JT.MBB != HeaderBB->getNextNode())
1657 MIB.buildBr(*JT.MBB);
1658 return true;
1659 }
1660
1661 // Emit the range check for the jump table, and branch to the default block
1662 // for the switch statement if the value being switched on exceeds the
1663 // largest case in the switch.
1664 auto Cst = getOrCreateVReg(
1665 *ConstantInt::get(SValue.getType(), JTH.Last - JTH.First));
1666 auto Cmp = MIB.buildICmp(CmpInst::ICMP_UGT, LLT::integer(1), Sub, Cst);
1667
1668 auto BrCond = MIB.buildBrCond(Cmp.getReg(0), *JT.Default);
1669
1670 // Avoid emitting unnecessary branches to the next block.
1671 if (JT.MBB != HeaderBB->getNextNode())
1672 BrCond = MIB.buildBr(*JT.MBB);
1673 return true;
1674}
1675
1676void IRTranslatorImpl::emitSwitchCase(SwitchCG::CaseBlock &CB,
1677 MachineBasicBlock *SwitchBB,
1678 MachineIRBuilder &MIB) {
1679 Register CondLHS = getOrCreateVReg(*CB.CmpLHS);
1680 Register Cond;
1681 DebugLoc OldDbgLoc = MIB.getDebugLoc();
1682 MIB.setDebugLoc(CB.DbgLoc);
1683 MIB.setMBB(*CB.ThisBB);
1684
1685 if (CB.PredInfo.NoCmp) {
1686 // Branch or fall through to TrueBB.
1687 addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
1688 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
1689 CB.ThisBB);
1691 if (CB.TrueBB != CB.ThisBB->getNextNode())
1692 MIB.buildBr(*CB.TrueBB);
1693 MIB.setDebugLoc(OldDbgLoc);
1694 return;
1695 }
1696
1697 const LLT i1Ty = LLT::integer(1);
1698 // Build the compare.
1699 if (!CB.CmpMHS) {
1700 const auto *CI = dyn_cast<ConstantInt>(CB.CmpRHS);
1701 // For conditional branch lowering, we might try to do something silly like
1702 // emit an G_ICMP to compare an existing G_ICMP i1 result with true. If so,
1703 // just re-use the existing condition vreg.
1704 if (MRI->getType(CondLHS).getSizeInBits() == 1 && CI && CI->isOne() &&
1706 Cond = CondLHS;
1707 } else {
1708 Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
1710 Cond =
1711 MIB.buildFCmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0);
1712 else
1713 Cond =
1714 MIB.buildICmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0);
1715 }
1716 } else {
1718 "Can only handle SLE ranges");
1719
1720 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1721 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1722
1723 Register CmpOpReg = getOrCreateVReg(*CB.CmpMHS);
1724 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1725 Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
1726 Cond =
1727 MIB.buildICmp(CmpInst::ICMP_SLE, i1Ty, CmpOpReg, CondRHS).getReg(0);
1728 } else {
1729 const LLT CmpTy = MRI->getType(CmpOpReg);
1730 auto Sub = MIB.buildSub({CmpTy}, CmpOpReg, CondLHS);
1731 auto Diff = MIB.buildConstant(CmpTy, High - Low);
1732 Cond = MIB.buildICmp(CmpInst::ICMP_ULE, i1Ty, Sub, Diff).getReg(0);
1733 }
1734 }
1735
1736 // Update successor info
1737 addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
1738
1739 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
1740 CB.ThisBB);
1741
1742 // TrueBB and FalseBB are always different unless the incoming IR is
1743 // degenerate. This only happens when running llc on weird IR.
1744 if (CB.TrueBB != CB.FalseBB)
1745 addSuccessorWithProb(CB.ThisBB, CB.FalseBB, CB.FalseProb);
1747
1748 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.FalseBB->getBasicBlock()},
1749 CB.ThisBB);
1750
1751 MIB.buildBrCond(Cond, *CB.TrueBB);
1752 MIB.buildBr(*CB.FalseBB);
1753 MIB.setDebugLoc(OldDbgLoc);
1754}
1755
1756bool IRTranslatorImpl::lowerJumpTableWorkItem(
1758 MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB,
1761 MachineBasicBlock *Fallthrough, bool FallthroughUnreachable) {
1762 using namespace SwitchCG;
1763 MachineFunction *CurMF = SwitchMBB->getParent();
1764 // FIXME: Optimize away range check based on pivot comparisons.
1765 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
1766 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
1767 BranchProbability DefaultProb = W.DefaultProb;
1768
1769 // The jump block hasn't been inserted yet; insert it here.
1770 MachineBasicBlock *JumpMBB = JT->MBB;
1771 CurMF->insert(BBI, JumpMBB);
1772
1773 // Since the jump table block is separate from the switch block, we need
1774 // to keep track of it as a machine predecessor to the default block,
1775 // otherwise we lose the phi edges.
1776 addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
1777 CurMBB);
1778 addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
1779 JumpMBB);
1780
1781 auto JumpProb = I->Prob;
1782 auto FallthroughProb = UnhandledProbs;
1783
1784 // If the default statement is a target of the jump table, we evenly
1785 // distribute the default probability to successors of CurMBB. Also
1786 // update the probability on the edge from JumpMBB to Fallthrough.
1787 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
1788 SE = JumpMBB->succ_end();
1789 SI != SE; ++SI) {
1790 if (*SI == DefaultMBB) {
1791 JumpProb += DefaultProb / 2;
1792 FallthroughProb -= DefaultProb / 2;
1793 JumpMBB->setSuccProbability(SI, DefaultProb / 2);
1794 JumpMBB->normalizeSuccProbs();
1795 } else {
1796 // Also record edges from the jump table block to it's successors.
1797 addMachineCFGPred({SwitchMBB->getBasicBlock(), (*SI)->getBasicBlock()},
1798 JumpMBB);
1799 }
1800 }
1801
1802 if (FallthroughUnreachable)
1803 JTH->FallthroughUnreachable = true;
1804
1805 if (!JTH->FallthroughUnreachable)
1806 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
1807 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
1808 CurMBB->normalizeSuccProbs();
1809
1810 // The jump table header will be inserted in our current block, do the
1811 // range check, and fall through to our fallthrough block.
1812 JTH->HeaderBB = CurMBB;
1813 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
1814
1815 // If we're in the right place, emit the jump table header right now.
1816 if (CurMBB == SwitchMBB) {
1817 if (!emitJumpTableHeader(*JT, *JTH, CurMBB))
1818 return false;
1819 JTH->Emitted = true;
1820 }
1821 return true;
1822}
1823bool IRTranslatorImpl::lowerSwitchRangeWorkItem(
1825 bool FallthroughUnreachable, BranchProbability UnhandledProbs,
1826 MachineBasicBlock *CurMBB, MachineIRBuilder &MIB,
1827 MachineBasicBlock *SwitchMBB) {
1828 using namespace SwitchCG;
1829 const Value *RHS, *LHS, *MHS;
1830 CmpInst::Predicate Pred;
1831 if (I->Low == I->High) {
1832 // Check Cond == I->Low.
1833 Pred = CmpInst::ICMP_EQ;
1834 LHS = Cond;
1835 RHS = I->Low;
1836 MHS = nullptr;
1837 } else {
1838 // Check I->Low <= Cond <= I->High.
1839 Pred = CmpInst::ICMP_SLE;
1840 LHS = I->Low;
1841 MHS = Cond;
1842 RHS = I->High;
1843 }
1844
1845 // If Fallthrough is unreachable, fold away the comparison.
1846 // The false probability is the sum of all unhandled cases.
1847 CaseBlock CB(Pred, FallthroughUnreachable, LHS, RHS, MHS, I->MBB, Fallthrough,
1848 CurMBB, MIB.getDebugLoc(), I->Prob, UnhandledProbs);
1849
1850 emitSwitchCase(CB, SwitchMBB, MIB);
1851 return true;
1852}
1853
1854void IRTranslatorImpl::emitBitTestHeader(SwitchCG::BitTestBlock &B,
1855 MachineBasicBlock *SwitchBB) {
1856 MachineIRBuilder &MIB = *CurBuilder;
1857 MIB.setMBB(*SwitchBB);
1858
1859 // Subtract the minimum value.
1860 Register SwitchOpReg = getOrCreateVReg(*B.SValue);
1861
1862 LLT SwitchOpTy = MRI->getType(SwitchOpReg);
1863 Register MinValReg = MIB.buildConstant(SwitchOpTy, B.First).getReg(0);
1864 auto RangeSub = MIB.buildSub(SwitchOpTy, SwitchOpReg, MinValReg);
1865
1866 Type *PtrIRTy = PointerType::getUnqual(MF->getFunction().getContext());
1867 const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
1868
1869 LLT MaskTy = SwitchOpTy;
1870 if (MaskTy.getSizeInBits() > PtrTy.getSizeInBits() ||
1872 MaskTy = LLT::integer(PtrTy.getSizeInBits());
1873 else {
1874 // Ensure that the type will fit the mask value.
1875 for (const SwitchCG::BitTestCase &Case : B.Cases) {
1876 if (!isUIntN(SwitchOpTy.getSizeInBits(), Case.Mask)) {
1877 // Switch table case range are encoded into series of masks.
1878 // Just use pointer type, it's guaranteed to fit.
1879 MaskTy = LLT::integer(PtrTy.getSizeInBits());
1880 break;
1881 }
1882 }
1883 }
1884 Register SubReg = RangeSub.getReg(0);
1885 if (SwitchOpTy != MaskTy)
1886 SubReg = MIB.buildZExtOrTrunc(MaskTy, SubReg).getReg(0);
1887
1888 B.RegVT = getMVTForLLT(MaskTy);
1889 B.Reg = SubReg;
1890
1891 MachineBasicBlock *MBB = B.Cases[0].ThisBB;
1892
1893 if (!B.FallthroughUnreachable)
1894 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
1895 addSuccessorWithProb(SwitchBB, MBB, B.Prob);
1896
1897 SwitchBB->normalizeSuccProbs();
1898
1899 if (!B.FallthroughUnreachable) {
1900 // Conditional branch to the default block.
1901 auto RangeCst = MIB.buildConstant(SwitchOpTy, B.Range);
1902 auto RangeCmp = MIB.buildICmp(CmpInst::Predicate::ICMP_UGT, LLT::integer(1),
1903 RangeSub, RangeCst);
1904 MIB.buildBrCond(RangeCmp, *B.Default);
1905 }
1906
1907 // Avoid emitting unnecessary branches to the next block.
1908 if (MBB != SwitchBB->getNextNode())
1909 MIB.buildBr(*MBB);
1910}
1911
1912void IRTranslatorImpl::emitBitTestCase(SwitchCG::BitTestBlock &BB,
1913 MachineBasicBlock *NextMBB,
1914 BranchProbability BranchProbToNext,
1916 MachineBasicBlock *SwitchBB) {
1917 MachineIRBuilder &MIB = *CurBuilder;
1918 MIB.setMBB(*SwitchBB);
1919
1920 LLT SwitchTy = getLLTForMVT(BB.RegVT);
1921 Register Cmp;
1922 unsigned PopCount = llvm::popcount(B.Mask);
1923 if (PopCount == 1) {
1924 // Testing for a single bit; just compare the shift count with what it
1925 // would need to be to shift a 1 bit in that position.
1926 auto MaskTrailingZeros =
1927 MIB.buildConstant(SwitchTy, llvm::countr_zero(B.Mask));
1929 MaskTrailingZeros)
1930 .getReg(0);
1931 } else if (PopCount == BB.Range) {
1932 // There is only one zero bit in the range, test for it directly.
1933 auto MaskTrailingOnes =
1934 MIB.buildConstant(SwitchTy, llvm::countr_one(B.Mask));
1935 Cmp =
1936 MIB.buildICmp(CmpInst::ICMP_NE, LLT::integer(1), Reg, MaskTrailingOnes)
1937 .getReg(0);
1938 } else {
1939 // Make desired shift.
1940 auto CstOne = MIB.buildConstant(SwitchTy, 1);
1941 auto SwitchVal = MIB.buildShl(SwitchTy, CstOne, Reg);
1942
1943 // Emit bit tests and jumps.
1944 auto CstMask = MIB.buildConstant(SwitchTy, B.Mask);
1945 auto AndOp = MIB.buildAnd(SwitchTy, SwitchVal, CstMask);
1946 auto CstZero = MIB.buildConstant(SwitchTy, 0);
1947 Cmp = MIB.buildICmp(CmpInst::ICMP_NE, LLT::integer(1), AndOp, CstZero)
1948 .getReg(0);
1949 }
1950
1951 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
1952 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
1953 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
1954 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
1955 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
1956 // one as they are relative probabilities (and thus work more like weights),
1957 // and hence we need to normalize them to let the sum of them become one.
1958 SwitchBB->normalizeSuccProbs();
1959
1960 // Record the fact that the IR edge from the header to the bit test target
1961 // will go through our new block. Neeeded for PHIs to have nodes added.
1962 addMachineCFGPred({BB.Parent->getBasicBlock(), B.TargetBB->getBasicBlock()},
1963 SwitchBB);
1964
1965 MIB.buildBrCond(Cmp, *B.TargetBB);
1966
1967 // Avoid emitting unnecessary branches to the next block.
1968 if (NextMBB != SwitchBB->getNextNode())
1969 MIB.buildBr(*NextMBB);
1970}
1971
1972bool IRTranslatorImpl::lowerBitTestWorkItem(
1974 MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB,
1976 BranchProbability DefaultProb, BranchProbability UnhandledProbs,
1978 bool FallthroughUnreachable) {
1979 using namespace SwitchCG;
1980 MachineFunction *CurMF = SwitchMBB->getParent();
1981 // FIXME: Optimize away range check based on pivot comparisons.
1982 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
1983 // The bit test blocks haven't been inserted yet; insert them here.
1984 for (BitTestCase &BTC : BTB->Cases)
1985 CurMF->insert(BBI, BTC.ThisBB);
1986
1987 // Fill in fields of the BitTestBlock.
1988 BTB->Parent = CurMBB;
1989 BTB->Default = Fallthrough;
1990
1991 BTB->DefaultProb = UnhandledProbs;
1992 // If the cases in bit test don't form a contiguous range, we evenly
1993 // distribute the probability on the edge to Fallthrough to two
1994 // successors of CurMBB.
1995 if (!BTB->ContiguousRange) {
1996 BTB->Prob += DefaultProb / 2;
1997 BTB->DefaultProb -= DefaultProb / 2;
1998 }
1999
2000 if (FallthroughUnreachable)
2001 BTB->FallthroughUnreachable = true;
2002
2003 // If we're in the right place, emit the bit test header right now.
2004 if (CurMBB == SwitchMBB) {
2005 emitBitTestHeader(*BTB, SwitchMBB);
2006 BTB->Emitted = true;
2007 }
2008 return true;
2009}
2010
2011bool IRTranslatorImpl::lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W,
2012 Value *Cond,
2013 MachineBasicBlock *SwitchMBB,
2014 MachineBasicBlock *DefaultMBB,
2015 MachineIRBuilder &MIB) {
2016 using namespace SwitchCG;
2017 MachineFunction *CurMF = FuncInfo.MF;
2018 MachineBasicBlock *NextMBB = nullptr;
2020 if (++BBI != FuncInfo.MF->end())
2021 NextMBB = &*BBI;
2022
2023 if (EnableOpts) {
2024 // Here, we order cases by probability so the most likely case will be
2025 // checked first. However, two clusters can have the same probability in
2026 // which case their relative ordering is non-deterministic. So we use Low
2027 // as a tie-breaker as clusters are guaranteed to never overlap.
2028 llvm::sort(W.FirstCluster, W.LastCluster + 1,
2029 [](const CaseCluster &a, const CaseCluster &b) {
2030 return a.Prob != b.Prob
2031 ? a.Prob > b.Prob
2032 : a.Low->getValue().slt(b.Low->getValue());
2033 });
2034
2035 // Rearrange the case blocks so that the last one falls through if possible
2036 // without changing the order of probabilities.
2037 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster;) {
2038 --I;
2039 if (I->Prob > W.LastCluster->Prob)
2040 break;
2041 if (I->Kind == CC_Range && I->MBB == NextMBB) {
2042 std::swap(*I, *W.LastCluster);
2043 break;
2044 }
2045 }
2046 }
2047
2048 // Compute total probability.
2049 BranchProbability DefaultProb = W.DefaultProb;
2050 BranchProbability UnhandledProbs = DefaultProb;
2051 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
2052 UnhandledProbs += I->Prob;
2053
2054 MachineBasicBlock *CurMBB = W.MBB;
2055 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
2056 bool FallthroughUnreachable = false;
2057 MachineBasicBlock *Fallthrough;
2058 if (I == W.LastCluster) {
2059 // For the last cluster, fall through to the default destination.
2060 Fallthrough = DefaultMBB;
2061 FallthroughUnreachable = isa<UnreachableInst>(
2062 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
2063 } else {
2064 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
2065 CurMF->insert(BBI, Fallthrough);
2066 }
2067 UnhandledProbs -= I->Prob;
2068
2069 switch (I->Kind) {
2070 case CC_BitTests: {
2071 if (!lowerBitTestWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
2072 DefaultProb, UnhandledProbs, I, Fallthrough,
2073 FallthroughUnreachable)) {
2074 LLVM_DEBUG(dbgs() << "Failed to lower bit test for switch");
2075 return false;
2076 }
2077 break;
2078 }
2079
2080 case CC_JumpTable: {
2081 if (!lowerJumpTableWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
2082 UnhandledProbs, I, Fallthrough,
2083 FallthroughUnreachable)) {
2084 LLVM_DEBUG(dbgs() << "Failed to lower jump table");
2085 return false;
2086 }
2087 break;
2088 }
2089 case CC_Range: {
2090 if (!lowerSwitchRangeWorkItem(I, Cond, Fallthrough,
2091 FallthroughUnreachable, UnhandledProbs,
2092 CurMBB, MIB, SwitchMBB)) {
2093 LLVM_DEBUG(dbgs() << "Failed to lower switch range");
2094 return false;
2095 }
2096 break;
2097 }
2098 }
2099 CurMBB = Fallthrough;
2100 }
2101
2102 return true;
2103}
2104
2105bool IRTranslatorImpl::translateIndirectBr(const User &U,
2106 MachineIRBuilder &MIRBuilder) {
2107 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
2108
2109 const Register Tgt = getOrCreateVReg(*BrInst.getAddress());
2110 MIRBuilder.buildBrIndirect(Tgt);
2111
2112 // Link successors.
2113 SmallPtrSet<const BasicBlock *, 32> AddedSuccessors;
2114 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
2115 for (const BasicBlock *Succ : successors(&BrInst)) {
2116 // It's legal for indirectbr instructions to have duplicate blocks in the
2117 // destination list. We don't allow this in MIR. Skip anything that's
2118 // already a successor.
2119 if (!AddedSuccessors.insert(Succ).second)
2120 continue;
2121 CurBB.addSuccessor(&getMBB(*Succ));
2122 }
2123
2124 return true;
2125}
2126
2127static bool isSwiftError(const Value *V) {
2128 if (auto Arg = dyn_cast<Argument>(V))
2129 return Arg->hasSwiftErrorAttr();
2130 if (auto AI = dyn_cast<AllocaInst>(V))
2131 return AI->isSwiftError();
2132 return false;
2133}
2134
2135bool IRTranslatorImpl::translateLoad(const User &U,
2136 MachineIRBuilder &MIRBuilder) {
2137 const LoadInst &LI = cast<LoadInst>(U);
2138 TypeSize StoreSize = DL->getTypeStoreSize(LI.getType());
2139 if (StoreSize.isZero())
2140 return true;
2141
2142 ArrayRef<Register> Regs = getOrCreateVRegs(LI);
2143 Register Base = getOrCreateVReg(*LI.getPointerOperand());
2144 AAMDNodes AAInfo = LI.getAAMetadata();
2145
2146 const Value *Ptr = LI.getPointerOperand();
2147
2148 if (CLI->supportSwiftError() && isSwiftError(Ptr)) {
2149 assert(Regs.size() == 1 && "swifterror should be single pointer");
2150 Register VReg =
2151 SwiftError.getOrCreateVRegUseAt(&LI, &MIRBuilder.getMBB(), Ptr);
2152 MIRBuilder.buildCopy(Regs[0], VReg);
2153 return true;
2154 }
2155
2157 TLI->getLoadMemOperandFlags(LI, *DL, AC, LibInfo, OptLevel);
2158 if (AA && !(Flags & MachineMemOperand::MOInvariant)) {
2159 if (AA->pointsToConstantMemory(
2160 MemoryLocation(Ptr, LocationSize::precise(StoreSize), AAInfo))) {
2162 }
2163 }
2164
2165 // Fast-path the common single-register load.
2166 if (Regs.size() == 1) {
2167 auto *MMO = MF->getMachineMemOperand(
2168 MachinePointerInfo(LI.getPointerOperand()), Flags,
2169 MRI->getType(Regs[0]), getMemOpAlign(LI),
2170 MMOMetadata(AAInfo, LI.getMetadata(LLVMContext::MD_range)),
2171 LI.getSyncScopeID(), LI.getOrdering());
2172 MIRBuilder.buildLoad(Regs[0], Base, *MMO);
2173 return true;
2174 }
2175
2176 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
2177 Type *OffsetIRTy = DL->getIndexType(Ptr->getType());
2178 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
2179 for (unsigned i = 0; i < Regs.size(); ++i) {
2180 Register Addr;
2181 MIRBuilder.materializeObjectPtrOffset(Addr, Base, OffsetTy, Offsets[i]);
2182
2183 MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i]);
2184 Align BaseAlign = getMemOpAlign(LI);
2185 auto *MMO =
2186 MF->getMachineMemOperand(Ptr, Flags, MRI->getType(Regs[i]),
2187 commonAlignment(BaseAlign, Offsets[i]), AAInfo,
2188 LI.getSyncScopeID(), LI.getOrdering());
2189 MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
2190 }
2191
2192 return true;
2193}
2194
2195bool IRTranslatorImpl::translateStore(const User &U,
2196 MachineIRBuilder &MIRBuilder) {
2197 const StoreInst &SI = cast<StoreInst>(U);
2198 if (DL->getTypeStoreSize(SI.getValueOperand()->getType()).isZero())
2199 return true;
2200
2201 ArrayRef<Register> Vals = getOrCreateVRegs(*SI.getValueOperand());
2202 Register Base = getOrCreateVReg(*SI.getPointerOperand());
2203
2204 if (CLI->supportSwiftError() && isSwiftError(SI.getPointerOperand())) {
2205 assert(Vals.size() == 1 && "swifterror should be single pointer");
2206
2207 Register VReg = SwiftError.getOrCreateVRegDefAt(&SI, &MIRBuilder.getMBB(),
2208 SI.getPointerOperand());
2209 MIRBuilder.buildCopy(VReg, Vals[0]);
2210 return true;
2211 }
2212
2213 MachineMemOperand::Flags Flags = TLI->getStoreMemOperandFlags(SI, *DL);
2214 // Fast-path the common single-register store.
2215 if (Vals.size() == 1) {
2216 auto *MMO = MF->getMachineMemOperand(
2217 MachinePointerInfo(SI.getPointerOperand()), Flags,
2218 MRI->getType(Vals[0]), getMemOpAlign(SI), SI.getAAMetadata(),
2219 SI.getSyncScopeID(), SI.getOrdering());
2220 MIRBuilder.buildStore(Vals[0], Base, *MMO);
2221 return true;
2222 }
2223
2224 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
2225 Type *OffsetIRTy = DL->getIndexType(SI.getPointerOperandType());
2226 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
2227 for (unsigned i = 0; i < Vals.size(); ++i) {
2228 Register Addr;
2229 MIRBuilder.materializeObjectPtrOffset(Addr, Base, OffsetTy, Offsets[i]);
2230
2231 MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i]);
2232 Align BaseAlign = getMemOpAlign(SI);
2233 auto *MMO = MF->getMachineMemOperand(Ptr, Flags, MRI->getType(Vals[i]),
2234 commonAlignment(BaseAlign, Offsets[i]),
2235 SI.getAAMetadata(),
2236 SI.getSyncScopeID(), SI.getOrdering());
2237 MIRBuilder.buildStore(Vals[i], Addr, *MMO);
2238 }
2239 return true;
2240}
2241
2243 const Value *Src = U.getOperand(0);
2244 Type *Int32Ty = Type::getInt32Ty(U.getContext());
2245
2246 // getIndexedOffsetInType is designed for GEPs, so the first index is the
2247 // usual array element rather than looking into the actual aggregate.
2249 Indices.push_back(ConstantInt::get(Int32Ty, 0));
2250
2251 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
2252 for (auto Idx : EVI->indices())
2253 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
2254 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
2255 for (auto Idx : IVI->indices())
2256 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
2257 } else {
2258 llvm::append_range(Indices, drop_begin(U.operands()));
2259 }
2260
2261 return static_cast<uint64_t>(
2262 DL.getIndexedOffsetInType(Src->getType(), Indices));
2263}
2264
2265bool IRTranslatorImpl::translateExtractValue(const User &U,
2266 MachineIRBuilder &MIRBuilder) {
2267 const Value *Src = U.getOperand(0);
2269 ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
2270 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
2271 unsigned Idx = llvm::lower_bound(Offsets, Offset) - Offsets.begin();
2272 auto &DstRegs = allocateVRegs(U);
2273
2274 for (unsigned i = 0; i < DstRegs.size(); ++i)
2275 DstRegs[i] = SrcRegs[Idx++];
2276
2277 return true;
2278}
2279
2280bool IRTranslatorImpl::translateInsertValue(const User &U,
2281 MachineIRBuilder &MIRBuilder) {
2282 const Value *Src = U.getOperand(0);
2284 auto &DstRegs = allocateVRegs(U);
2285 ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
2286 ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
2287 ArrayRef<Register> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
2288 auto *InsertedIt = InsertedRegs.begin();
2289
2290 for (unsigned i = 0; i < DstRegs.size(); ++i) {
2291 if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
2292 DstRegs[i] = *InsertedIt++;
2293 else
2294 DstRegs[i] = SrcRegs[i];
2295 }
2296
2297 return true;
2298}
2299
2300bool IRTranslatorImpl::translateSelect(const User &U,
2301 MachineIRBuilder &MIRBuilder) {
2302 Register Tst = getOrCreateVReg(*U.getOperand(0));
2303 ArrayRef<Register> ResRegs = getOrCreateVRegs(U);
2304 ArrayRef<Register> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
2305 ArrayRef<Register> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
2306
2307 uint32_t Flags = 0;
2308 if (const SelectInst *SI = dyn_cast<SelectInst>(&U))
2310
2311 for (unsigned i = 0; i < ResRegs.size(); ++i) {
2312 MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i], Flags);
2313 }
2314
2315 return true;
2316}
2317
2318bool IRTranslatorImpl::translateCopy(const User &U, const Value &V,
2319 MachineIRBuilder &MIRBuilder) {
2320 return translateCopy(U, getOrCreateVReg(V), MIRBuilder);
2321}
2322
2323bool IRTranslatorImpl::translateCopy(const User &U, Register Src,
2324 MachineIRBuilder &MIRBuilder) {
2325 auto &Regs = *VMap.getVRegs(U);
2326 if (Regs.empty()) {
2327 Regs.push_back(Src);
2328 } else {
2329 // If we already assigned a vreg for this instruction, we can't change that.
2330 // Emit a copy to satisfy the users we already emitted.
2331 MIRBuilder.buildCopy(Regs[0], Src);
2332 }
2333 return true;
2334}
2335
2336bool IRTranslatorImpl::translateBitCast(const User &U,
2337 MachineIRBuilder &MIRBuilder) {
2338 Type *SrcTy = U.getOperand(0)->getType();
2339 Type *DstTy = U.getType();
2340
2341 // If we're bitcasting to the source type, we can reuse the source vreg.
2342 if (getLLTForType(*SrcTy, *DL) == getLLTForType(*DstTy, *DL)) {
2343 // If the source is a ConstantInt then it was probably created by
2344 // ConstantHoisting and we should leave it alone.
2345 if (isa<ConstantInt>(U.getOperand(0)))
2346 return translateCast(TargetOpcode::G_CONSTANT_FOLD_BARRIER, U,
2347 MIRBuilder);
2348 return translateCopy(U, *U.getOperand(0), MIRBuilder);
2349 }
2350
2351 // Only the scalar byte<->ptr crossing is redirected to G_INTTOPTR/G_PTRTOINT,
2352 // which is the well-typed MIR shape for that boundary. Vector byte<->ptr
2353 // (e.g. <N x b32> -> ptr produced by mixed-type load coalescing) and other
2354 // legacy ptr/non-ptr IR bitcasts (AMDGPU iN<->p3 kernarg packing, etc.)
2355 // keep their historical G_BITCAST lowering — G_INTTOPTR has no vector-src
2356 // -> scalar-ptr form, and downstream passes already handle G_BITCAST.
2357 if (DstTy->isPointerTy() && SrcTy->isByteTy())
2358 return translateCast(TargetOpcode::G_INTTOPTR, U, MIRBuilder);
2359 if (SrcTy->isPointerTy() && DstTy->isByteTy())
2360 return translateCast(TargetOpcode::G_PTRTOINT, U, MIRBuilder);
2361
2362 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
2363}
2364
2365bool IRTranslatorImpl::translateCast(unsigned Opcode, const User &U,
2366 MachineIRBuilder &MIRBuilder) {
2367 if (!mayTranslateUserTypes(U))
2368 return false;
2369
2370 uint32_t Flags = 0;
2371 if (const Instruction *I = dyn_cast<Instruction>(&U))
2373
2374 Register Op = getOrCreateVReg(*U.getOperand(0));
2375 Register Res = getOrCreateVReg(U);
2376 MIRBuilder.buildInstr(Opcode, {Res}, {Op}, Flags);
2377 return true;
2378}
2379
2380bool IRTranslatorImpl::translateGetElementPtr(const User &U,
2381 MachineIRBuilder &MIRBuilder) {
2382 Value &Op0 = *U.getOperand(0);
2383 Register BaseReg = getOrCreateVReg(Op0);
2384 Type *PtrIRTy = Op0.getType();
2385 LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
2386 Type *OffsetIRTy = DL->getIndexType(PtrIRTy);
2387 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
2388
2389 uint32_t PtrAddFlags = 0;
2390 // Each PtrAdd generated to implement the GEP inherits its nuw, nusw, inbounds
2391 // flags.
2392 if (const Instruction *I = dyn_cast<Instruction>(&U))
2394
2395 auto PtrAddFlagsWithConst = [&](int64_t Offset) {
2396 // For nusw/inbounds GEP with an offset that is nonnegative when interpreted
2397 // as signed, assume there is no unsigned overflow.
2398 if (Offset >= 0 && (PtrAddFlags & MachineInstr::MIFlag::NoUSWrap))
2399 return PtrAddFlags | MachineInstr::MIFlag::NoUWrap;
2400 return PtrAddFlags;
2401 };
2402
2403 // Normalize Vector GEP - all scalar operands should be converted to the
2404 // splat vector.
2405 unsigned VectorWidth = 0;
2406
2407 // True if we should use a splat vector; using VectorWidth alone is not
2408 // sufficient.
2409 bool WantSplatVector = false;
2410 if (auto *VT = dyn_cast<VectorType>(U.getType())) {
2411 VectorWidth = cast<FixedVectorType>(VT)->getNumElements();
2412 // We don't produce 1 x N vectors; those are treated as scalars.
2413 WantSplatVector = VectorWidth > 1;
2414 }
2415
2416 if (cast<GEPOperator>(U).hasAllZeroIndices())
2417 return translateCopy(U, BaseReg, MIRBuilder);
2418
2419 // We might need to splat the base pointer into a vector if the offsets
2420 // are vectors.
2421 if (WantSplatVector && !PtrTy.isVector()) {
2422 BaseReg = MIRBuilder
2423 .buildSplatBuildVector(LLT::fixed_vector(VectorWidth, PtrTy),
2424 BaseReg)
2425 .getReg(0);
2426 PtrIRTy = FixedVectorType::get(PtrIRTy, VectorWidth);
2427 PtrTy = getLLTForType(*PtrIRTy, *DL);
2428 OffsetIRTy = DL->getIndexType(PtrIRTy);
2429 OffsetTy = getLLTForType(*OffsetIRTy, *DL);
2430 }
2431
2432 int64_t Offset = 0;
2433 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
2434 GTI != E; ++GTI) {
2435 const Value *Idx = GTI.getOperand();
2436 if (StructType *StTy = GTI.getStructTypeOrNull()) {
2437 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
2438 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
2439 continue;
2440 } else {
2441 uint64_t ElementSize = GTI.getSequentialElementStride(*DL);
2442
2443 // If this is a scalar constant or a splat vector of constants,
2444 // handle it quickly.
2445 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
2446 if (std::optional<int64_t> Val = CI->getValue().trySExtValue()) {
2447 Offset += ElementSize * *Val;
2448 continue;
2449 }
2450 }
2451
2452 if (Offset != 0) {
2453 auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset);
2454 BaseReg = MIRBuilder
2455 .buildPtrAdd(PtrTy, BaseReg, OffsetMIB.getReg(0),
2456 PtrAddFlagsWithConst(Offset))
2457 .getReg(0);
2458 Offset = 0;
2459 }
2460
2461 Register IdxReg = getOrCreateVReg(*Idx);
2462 LLT IdxTy = MRI->getType(IdxReg);
2463 if (IdxTy != OffsetTy) {
2464 if (!IdxTy.isVector() && WantSplatVector) {
2465 IdxReg = MIRBuilder
2467 IdxReg)
2468 .getReg(0);
2469 }
2470
2471 IdxReg = MIRBuilder.buildSExtOrTrunc(OffsetTy, IdxReg).getReg(0);
2472 }
2473
2474 // N = N + Idx * ElementSize;
2475 // Avoid doing it for ElementSize of 1.
2476 Register GepOffsetReg;
2477 if (ElementSize != 1) {
2478 auto ElementSizeMIB = MIRBuilder.buildConstant(
2479 getLLTForType(*OffsetIRTy, *DL), ElementSize);
2480
2481 // The multiplication is NUW if the GEP is NUW and NSW if the GEP is
2482 // NUSW.
2483 uint32_t ScaleFlags = PtrAddFlags & MachineInstr::MIFlag::NoUWrap;
2484 if (PtrAddFlags & MachineInstr::MIFlag::NoUSWrap)
2485 ScaleFlags |= MachineInstr::MIFlag::NoSWrap;
2486
2487 GepOffsetReg =
2488 MIRBuilder.buildMul(OffsetTy, IdxReg, ElementSizeMIB, ScaleFlags)
2489 .getReg(0);
2490 } else {
2491 GepOffsetReg = IdxReg;
2492 }
2493
2494 BaseReg =
2495 MIRBuilder.buildPtrAdd(PtrTy, BaseReg, GepOffsetReg, PtrAddFlags)
2496 .getReg(0);
2497 }
2498 }
2499
2500 if (Offset != 0) {
2501 auto OffsetMIB =
2502 MIRBuilder.buildConstant(OffsetTy, Offset);
2503
2504 MIRBuilder.buildPtrAdd(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0),
2505 PtrAddFlagsWithConst(Offset));
2506 return true;
2507 }
2508
2509 return translateCopy(U, BaseReg, MIRBuilder);
2510}
2511
2512bool IRTranslatorImpl::translateMemFunc(const CallInst &CI,
2513 MachineIRBuilder &MIRBuilder,
2514 unsigned Opcode) {
2515 const Value *SrcPtr = CI.getArgOperand(1);
2516 // If the source is undef, then just emit a nop.
2517 if (isa<UndefValue>(SrcPtr))
2518 return true;
2519
2521
2522 unsigned MinPtrSize = UINT_MAX;
2523 for (auto AI = CI.arg_begin(), AE = CI.arg_end(); std::next(AI) != AE; ++AI) {
2524 Register SrcReg = getOrCreateVReg(**AI);
2525 LLT SrcTy = MRI->getType(SrcReg);
2526 if (SrcTy.isPointer())
2527 MinPtrSize = std::min<unsigned>(SrcTy.getSizeInBits(), MinPtrSize);
2528 SrcRegs.push_back(SrcReg);
2529 }
2530
2531 LLT SizeTy = LLT::integer(MinPtrSize);
2532
2533 // The size operand should be the minimum of the pointer sizes.
2534 Register &SizeOpReg = SrcRegs[SrcRegs.size() - 1];
2535 if (MRI->getType(SizeOpReg) != SizeTy)
2536 SizeOpReg = MIRBuilder.buildZExtOrTrunc(SizeTy, SizeOpReg).getReg(0);
2537
2538 auto ICall = MIRBuilder.buildInstr(Opcode);
2539 for (Register SrcReg : SrcRegs)
2540 ICall.addUse(SrcReg);
2541
2542 Align DstAlign;
2543 Align SrcAlign;
2544 unsigned IsVol =
2545 cast<ConstantInt>(CI.getArgOperand(CI.arg_size() - 1))->getZExtValue();
2546
2547 ConstantInt *CopySize = nullptr;
2548
2549 if (auto *MCI = dyn_cast<MemCpyInst>(&CI)) {
2550 DstAlign = MCI->getDestAlign().valueOrOne();
2551 SrcAlign = MCI->getSourceAlign().valueOrOne();
2552 CopySize = dyn_cast<ConstantInt>(MCI->getArgOperand(2));
2553 } else if (auto *MMI = dyn_cast<MemMoveInst>(&CI)) {
2554 DstAlign = MMI->getDestAlign().valueOrOne();
2555 SrcAlign = MMI->getSourceAlign().valueOrOne();
2556 CopySize = dyn_cast<ConstantInt>(MMI->getArgOperand(2));
2557 } else {
2558 auto *MSI = cast<MemSetInst>(&CI);
2559 DstAlign = MSI->getDestAlign().valueOrOne();
2560 }
2561
2562 if (Opcode != TargetOpcode::G_MEMCPY_INLINE &&
2563 Opcode != TargetOpcode::G_MEMSET_INLINE) {
2564 // We need to propagate the tail call flag from the IR inst as an argument.
2565 // Otherwise, we have to pessimize and assume later that we cannot tail call
2566 // any memory intrinsics.
2567 ICall.addImm(CI.isTailCall() ? 1 : 0);
2568 }
2569
2570 // Create mem operands to store the alignment and volatile info.
2573 if (IsVol) {
2574 LoadFlags |= MachineMemOperand::MOVolatile;
2575 StoreFlags |= MachineMemOperand::MOVolatile;
2576 }
2577
2578 AAMDNodes AAInfo = CI.getAAMetadata();
2579 if (AA && CopySize &&
2580 AA->pointsToConstantMemory(MemoryLocation(
2581 SrcPtr, LocationSize::precise(CopySize->getZExtValue()), AAInfo))) {
2582 LoadFlags |= MachineMemOperand::MOInvariant;
2583
2584 // FIXME: pointsToConstantMemory probably does not imply dereferenceable,
2585 // but the previous usage implied it did. Probably should check
2586 // isDereferenceableAndAlignedPointer.
2588 }
2589
2590 ICall.addMemOperand(
2591 MF->getMachineMemOperand(MachinePointerInfo(CI.getArgOperand(0)),
2592 StoreFlags, 1, DstAlign, AAInfo));
2593 if (Opcode != TargetOpcode::G_MEMSET &&
2594 Opcode != TargetOpcode::G_MEMSET_INLINE)
2595 ICall.addMemOperand(MF->getMachineMemOperand(
2596 MachinePointerInfo(SrcPtr), LoadFlags, 1, SrcAlign, AAInfo));
2597
2598 return true;
2599}
2600
2601bool IRTranslatorImpl::translateTrap(const CallInst &CI,
2602 MachineIRBuilder &MIRBuilder,
2603 unsigned Opcode) {
2604 StringRef TrapFuncName =
2605 CI.getAttributes().getFnAttr("trap-func-name").getValueAsString();
2606 if (TrapFuncName.empty()) {
2607 if (Opcode == TargetOpcode::G_UBSANTRAP) {
2608 uint64_t Code = cast<ConstantInt>(CI.getOperand(0))->getZExtValue();
2609 MIRBuilder.buildInstr(Opcode, {}, ArrayRef<llvm::SrcOp>{Code});
2610 } else {
2611 MIRBuilder.buildInstr(Opcode);
2612 }
2613 return true;
2614 }
2615
2616 CallLowering::CallLoweringInfo Info;
2617 if (Opcode == TargetOpcode::G_UBSANTRAP)
2618 Info.OrigArgs.push_back({getOrCreateVRegs(*CI.getArgOperand(0)),
2619 CI.getArgOperand(0)->getType(), 0});
2620
2621 Info.Callee = MachineOperand::CreateES(TrapFuncName.data());
2622 Info.CB = &CI;
2623 Info.OrigRet = {Register(), Type::getVoidTy(CI.getContext()), 0};
2624 return CLI->lowerCall(MIRBuilder, Info);
2625}
2626
2627bool IRTranslatorImpl::translateVectorInterleave2Intrinsic(
2628 const CallInst &CI, MachineIRBuilder &MIRBuilder) {
2629 assert(CI.getIntrinsicID() == Intrinsic::vector_interleave2 &&
2630 "This function can only be called on the interleave2 intrinsic!");
2631 // Canonicalize interleave2 to G_SHUFFLE_VECTOR (similar to SelectionDAG).
2632 Register Op0 = getOrCreateVReg(*CI.getOperand(0));
2633 Register Op1 = getOrCreateVReg(*CI.getOperand(1));
2634 Register Res = getOrCreateVReg(CI);
2635
2636 LLT OpTy = MRI->getType(Op0);
2637 MIRBuilder.buildShuffleVector(Res, Op0, Op1,
2639
2640 return true;
2641}
2642
2643bool IRTranslatorImpl::translateVectorDeinterleave2Intrinsic(
2644 const CallInst &CI, MachineIRBuilder &MIRBuilder) {
2645 assert(CI.getIntrinsicID() == Intrinsic::vector_deinterleave2 &&
2646 "This function can only be called on the deinterleave2 intrinsic!");
2647 // Canonicalize deinterleave2 to shuffles that extract sub-vectors (similar to
2648 // SelectionDAG).
2649 Register Op = getOrCreateVReg(*CI.getOperand(0));
2650 auto Undef = MIRBuilder.buildUndef(MRI->getType(Op));
2651 ArrayRef<Register> Res = getOrCreateVRegs(CI);
2652
2653 LLT ResTy = MRI->getType(Res[0]);
2654 if (ResTy.isScalar()) {
2655 MIRBuilder.buildExtractVectorElementConstant(Res[0], Op, 0);
2656 MIRBuilder.buildExtractVectorElementConstant(Res[1], Op, 1);
2657
2658 return true;
2659 }
2660
2661 assert(ResTy.isVector() && "Expected vector result type");
2662 MIRBuilder.buildShuffleVector(Res[0], Op, Undef,
2663 createStrideMask(0, 2, ResTy.getNumElements()));
2664 MIRBuilder.buildShuffleVector(Res[1], Op, Undef,
2665 createStrideMask(1, 2, ResTy.getNumElements()));
2666
2667 return true;
2668}
2669
2670void IRTranslatorImpl::getStackGuard(Register DstReg,
2671 MachineIRBuilder &MIRBuilder) {
2672 Value *Global =
2673 TLI->getSDagStackGuard(*MF->getFunction().getParent(), *Libcalls);
2674 if (!Global) {
2675 LLVMContext &Ctx = MIRBuilder.getContext();
2676 Ctx.diagnose(DiagnosticInfoGeneric("unable to lower stackguard"));
2677 MIRBuilder.buildUndef(DstReg);
2678 return;
2679 }
2680
2681 const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
2682 MRI->setRegClass(DstReg,
2683 TII.getRegClass(TII.get(TargetOpcode::LOAD_STACK_GUARD), 0));
2684 auto MIB =
2685 MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD, {DstReg}, {});
2686
2687 unsigned AddrSpace = Global->getType()->getPointerAddressSpace();
2688 LLT PtrTy = LLT::pointer(AddrSpace, DL->getPointerSizeInBits(AddrSpace));
2689
2690 MachinePointerInfo MPInfo(Global);
2693 MachineMemOperand *MemRef = MF->getMachineMemOperand(
2694 MPInfo, Flags, PtrTy, DL->getPointerABIAlignment(AddrSpace));
2695 MIB.setMemRefs({MemRef});
2696}
2697
2698bool IRTranslatorImpl::translateOverflowIntrinsic(
2699 const CallInst &CI, unsigned Op, MachineIRBuilder &MIRBuilder) {
2700 ArrayRef<Register> ResRegs = getOrCreateVRegs(CI);
2701 MIRBuilder.buildInstr(
2702 Op, {ResRegs[0], ResRegs[1]},
2703 {getOrCreateVReg(*CI.getOperand(0)), getOrCreateVReg(*CI.getOperand(1))});
2704
2705 return true;
2706}
2707
2708bool IRTranslatorImpl::translateFixedPointIntrinsic(
2709 unsigned Op, const CallInst &CI, MachineIRBuilder &MIRBuilder) {
2710 Register Dst = getOrCreateVReg(CI);
2711 Register Src0 = getOrCreateVReg(*CI.getOperand(0));
2712 Register Src1 = getOrCreateVReg(*CI.getOperand(1));
2713 uint64_t Scale = cast<ConstantInt>(CI.getOperand(2))->getZExtValue();
2714 MIRBuilder.buildInstr(Op, {Dst}, { Src0, Src1, Scale });
2715 return true;
2716}
2717
2718unsigned IRTranslatorImpl::getSimpleIntrinsicOpcode(Intrinsic::ID ID) {
2719 switch (ID) {
2720 default:
2721 break;
2722 case Intrinsic::acos:
2723 return TargetOpcode::G_FACOS;
2724 case Intrinsic::asin:
2725 return TargetOpcode::G_FASIN;
2726 case Intrinsic::atan:
2727 return TargetOpcode::G_FATAN;
2728 case Intrinsic::atan2:
2729 return TargetOpcode::G_FATAN2;
2730 case Intrinsic::bswap:
2731 return TargetOpcode::G_BSWAP;
2732 case Intrinsic::bitreverse:
2733 return TargetOpcode::G_BITREVERSE;
2734 case Intrinsic::clmul:
2735 return TargetOpcode::G_CLMUL;
2736 case Intrinsic::fshl:
2737 return TargetOpcode::G_FSHL;
2738 case Intrinsic::fshr:
2739 return TargetOpcode::G_FSHR;
2740 case Intrinsic::ceil:
2741 return TargetOpcode::G_FCEIL;
2742 case Intrinsic::cos:
2743 return TargetOpcode::G_FCOS;
2744 case Intrinsic::cosh:
2745 return TargetOpcode::G_FCOSH;
2746 case Intrinsic::ctpop:
2747 return TargetOpcode::G_CTPOP;
2748 case Intrinsic::smulh:
2749 return TargetOpcode::G_SMULH;
2750 case Intrinsic::umulh:
2751 return TargetOpcode::G_UMULH;
2752 case Intrinsic::exp:
2753 return TargetOpcode::G_FEXP;
2754 case Intrinsic::exp2:
2755 return TargetOpcode::G_FEXP2;
2756 case Intrinsic::exp10:
2757 return TargetOpcode::G_FEXP10;
2758 case Intrinsic::fabs:
2759 return TargetOpcode::G_FABS;
2760 case Intrinsic::copysign:
2761 return TargetOpcode::G_FCOPYSIGN;
2762 case Intrinsic::minnum:
2763 return TargetOpcode::G_FMINNUM;
2764 case Intrinsic::maxnum:
2765 return TargetOpcode::G_FMAXNUM;
2766 case Intrinsic::minimum:
2767 return TargetOpcode::G_FMINIMUM;
2768 case Intrinsic::maximum:
2769 return TargetOpcode::G_FMAXIMUM;
2770 case Intrinsic::minimumnum:
2771 return TargetOpcode::G_FMINIMUMNUM;
2772 case Intrinsic::maximumnum:
2773 return TargetOpcode::G_FMAXIMUMNUM;
2774 case Intrinsic::canonicalize:
2775 return TargetOpcode::G_FCANONICALIZE;
2776 case Intrinsic::floor:
2777 return TargetOpcode::G_FFLOOR;
2778 case Intrinsic::fma:
2779 return TargetOpcode::G_FMA;
2780 case Intrinsic::log:
2781 return TargetOpcode::G_FLOG;
2782 case Intrinsic::log2:
2783 return TargetOpcode::G_FLOG2;
2784 case Intrinsic::log10:
2785 return TargetOpcode::G_FLOG10;
2786 case Intrinsic::ldexp:
2787 return TargetOpcode::G_FLDEXP;
2788 case Intrinsic::nearbyint:
2789 return TargetOpcode::G_FNEARBYINT;
2790 case Intrinsic::pow:
2791 return TargetOpcode::G_FPOW;
2792 case Intrinsic::powi:
2793 return TargetOpcode::G_FPOWI;
2794 case Intrinsic::rint:
2795 return TargetOpcode::G_FRINT;
2796 case Intrinsic::round:
2797 return TargetOpcode::G_INTRINSIC_ROUND;
2798 case Intrinsic::roundeven:
2799 return TargetOpcode::G_INTRINSIC_ROUNDEVEN;
2800 case Intrinsic::sin:
2801 return TargetOpcode::G_FSIN;
2802 case Intrinsic::sinh:
2803 return TargetOpcode::G_FSINH;
2804 case Intrinsic::sqrt:
2805 return TargetOpcode::G_FSQRT;
2806 case Intrinsic::tan:
2807 return TargetOpcode::G_FTAN;
2808 case Intrinsic::tanh:
2809 return TargetOpcode::G_FTANH;
2810 case Intrinsic::trunc:
2811 return TargetOpcode::G_INTRINSIC_TRUNC;
2812 case Intrinsic::readcyclecounter:
2813 return TargetOpcode::G_READCYCLECOUNTER;
2814 case Intrinsic::readsteadycounter:
2815 return TargetOpcode::G_READSTEADYCOUNTER;
2816 case Intrinsic::ptrmask:
2817 return TargetOpcode::G_PTRMASK;
2818 case Intrinsic::lrint:
2819 return TargetOpcode::G_INTRINSIC_LRINT;
2820 case Intrinsic::llrint:
2821 return TargetOpcode::G_INTRINSIC_LLRINT;
2822 // FADD/FMUL require checking the FMF, so are handled elsewhere.
2823 case Intrinsic::vector_reduce_fmin:
2824 return TargetOpcode::G_VECREDUCE_FMIN;
2825 case Intrinsic::vector_reduce_fmax:
2826 return TargetOpcode::G_VECREDUCE_FMAX;
2827 case Intrinsic::vector_reduce_fminimum:
2828 return TargetOpcode::G_VECREDUCE_FMINIMUM;
2829 case Intrinsic::vector_reduce_fmaximum:
2830 return TargetOpcode::G_VECREDUCE_FMAXIMUM;
2831 case Intrinsic::vector_reduce_fminimumnum:
2832 return TargetOpcode::G_VECREDUCE_FMINIMUMNUM;
2833 case Intrinsic::vector_reduce_fmaximumnum:
2834 return TargetOpcode::G_VECREDUCE_FMAXIMUMNUM;
2835 case Intrinsic::vector_reduce_add:
2836 return TargetOpcode::G_VECREDUCE_ADD;
2837 case Intrinsic::vector_reduce_mul:
2838 return TargetOpcode::G_VECREDUCE_MUL;
2839 case Intrinsic::vector_reduce_and:
2840 return TargetOpcode::G_VECREDUCE_AND;
2841 case Intrinsic::vector_reduce_or:
2842 return TargetOpcode::G_VECREDUCE_OR;
2843 case Intrinsic::vector_reduce_xor:
2844 return TargetOpcode::G_VECREDUCE_XOR;
2845 case Intrinsic::vector_reduce_smax:
2846 return TargetOpcode::G_VECREDUCE_SMAX;
2847 case Intrinsic::vector_reduce_smin:
2848 return TargetOpcode::G_VECREDUCE_SMIN;
2849 case Intrinsic::vector_reduce_umax:
2850 return TargetOpcode::G_VECREDUCE_UMAX;
2851 case Intrinsic::vector_reduce_umin:
2852 return TargetOpcode::G_VECREDUCE_UMIN;
2853 case Intrinsic::experimental_vector_compress:
2854 return TargetOpcode::G_VECTOR_COMPRESS;
2855 case Intrinsic::lround:
2856 return TargetOpcode::G_LROUND;
2857 case Intrinsic::llround:
2858 return TargetOpcode::G_LLROUND;
2859 case Intrinsic::get_fpenv:
2860 return TargetOpcode::G_GET_FPENV;
2861 case Intrinsic::get_fpmode:
2862 return TargetOpcode::G_GET_FPMODE;
2863 }
2865}
2866
2867bool IRTranslatorImpl::translateSimpleIntrinsic(const CallInst &CI,
2868 Intrinsic::ID ID,
2869 MachineIRBuilder &MIRBuilder) {
2870
2871 unsigned Op = getSimpleIntrinsicOpcode(ID);
2872
2873 // Is this a simple intrinsic?
2875 return false;
2876
2877 // Yes. Let's translate it.
2879 for (const auto &Arg : CI.args())
2880 VRegs.push_back(getOrCreateVReg(*Arg));
2881
2882 MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
2884 return true;
2885}
2886
2887// TODO: Include ConstainedOps.def when all strict instructions are defined.
2889 switch (ID) {
2890 case Intrinsic::experimental_constrained_fadd:
2891 return TargetOpcode::G_STRICT_FADD;
2892 case Intrinsic::experimental_constrained_fsub:
2893 return TargetOpcode::G_STRICT_FSUB;
2894 case Intrinsic::experimental_constrained_fmul:
2895 return TargetOpcode::G_STRICT_FMUL;
2896 case Intrinsic::experimental_constrained_fdiv:
2897 return TargetOpcode::G_STRICT_FDIV;
2898 case Intrinsic::experimental_constrained_frem:
2899 return TargetOpcode::G_STRICT_FREM;
2900 case Intrinsic::experimental_constrained_fma:
2901 return TargetOpcode::G_STRICT_FMA;
2902 case Intrinsic::experimental_constrained_sqrt:
2903 return TargetOpcode::G_STRICT_FSQRT;
2904 case Intrinsic::experimental_constrained_ldexp:
2905 return TargetOpcode::G_STRICT_FLDEXP;
2906 case Intrinsic::experimental_constrained_fcmp:
2907 return TargetOpcode::G_STRICT_FCMP;
2908 case Intrinsic::experimental_constrained_fcmps:
2909 return TargetOpcode::G_STRICT_FCMPS;
2910 default:
2911 return 0;
2912 }
2913}
2914
2915bool IRTranslatorImpl::translateConstrainedFPIntrinsic(
2916 const ConstrainedFPIntrinsic &FPI, MachineIRBuilder &MIRBuilder) {
2918
2919 unsigned Opcode = getConstrainedOpcode(FPI.getIntrinsicID());
2920 if (!Opcode)
2921 return false;
2922
2926
2927 if (Opcode == TargetOpcode::G_STRICT_FCMP ||
2928 Opcode == TargetOpcode::G_STRICT_FCMPS) {
2929 auto *FPCmp = cast<ConstrainedFPCmpIntrinsic>(&FPI);
2930 Register Operand0 = getOrCreateVReg(*FPCmp->getArgOperand(0));
2931 Register Operand1 = getOrCreateVReg(*FPCmp->getArgOperand(1));
2932 Register Result = getOrCreateVReg(FPI);
2933 MIRBuilder.buildInstr(Opcode, {Result}, {}, Flags)
2934 .addPredicate(FPCmp->getPredicate())
2935 .addUse(Operand0)
2936 .addUse(Operand1);
2937 return true;
2938 }
2939
2941 for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
2942 VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(I)));
2943
2944 MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(FPI)}, VRegs, Flags);
2945 return true;
2946}
2947
2948std::optional<MCRegister> IRTranslatorImpl::getArgPhysReg(Argument &Arg) {
2949 auto VRegs = getOrCreateVRegs(Arg);
2950 if (VRegs.size() != 1)
2951 return std::nullopt;
2952
2953 // Arguments are lowered as a copy of a livein physical register.
2954 auto *VRegDef = MF->getRegInfo().getVRegDef(VRegs[0]);
2955 if (!VRegDef || !VRegDef->isCopy())
2956 return std::nullopt;
2957 return VRegDef->getOperand(1).getReg().asMCReg();
2958}
2959
2960bool IRTranslatorImpl::translateIfEntryValueArgument(
2961 bool isDeclare, Value *Val, const DILocalVariable *Var,
2962 const DIExpression *Expr, const DebugLoc &DL,
2963 MachineIRBuilder &MIRBuilder) {
2964 auto *Arg = dyn_cast<Argument>(Val);
2965 if (!Arg)
2966 return false;
2967
2968 if (!Expr->isEntryValue())
2969 return false;
2970
2971 std::optional<MCRegister> PhysReg = getArgPhysReg(*Arg);
2972 if (!PhysReg) {
2973 LLVM_DEBUG(dbgs() << "Dropping dbg." << (isDeclare ? "declare" : "value")
2974 << ": expression is entry_value but "
2975 << "couldn't find a physical register\n");
2976 LLVM_DEBUG(dbgs() << *Var << "\n");
2977 return true;
2978 }
2979
2980 if (isDeclare) {
2981 // Append an op deref to account for the fact that this is a dbg_declare.
2982 Expr = DIExpression::append(Expr, dwarf::DW_OP_deref);
2983 MF->setVariableDbgInfo(Var, Expr, *PhysReg, DL);
2984 } else {
2985 MIRBuilder.buildDirectDbgValue(*PhysReg, Var, Expr);
2986 }
2987
2988 return true;
2989}
2990
2991static unsigned getConvOpcode(Intrinsic::ID ID) {
2992 switch (ID) {
2993 default:
2994 llvm_unreachable("Unexpected intrinsic");
2995 case Intrinsic::experimental_convergence_anchor:
2996 return TargetOpcode::CONVERGENCECTRL_ANCHOR;
2997 case Intrinsic::experimental_convergence_entry:
2998 return TargetOpcode::CONVERGENCECTRL_ENTRY;
2999 case Intrinsic::experimental_convergence_loop:
3000 return TargetOpcode::CONVERGENCECTRL_LOOP;
3001 }
3002}
3003
3004bool IRTranslatorImpl::translateConvergenceControlIntrinsic(
3005 const CallInst &CI, Intrinsic::ID ID, MachineIRBuilder &MIRBuilder) {
3006 MachineInstrBuilder MIB = MIRBuilder.buildInstr(getConvOpcode(ID));
3007 Register OutputReg = getOrCreateConvergenceTokenVReg(CI);
3008 MIB.addDef(OutputReg);
3009
3010 if (ID == Intrinsic::experimental_convergence_loop) {
3012 assert(Bundle && "Expected a convergence control token.");
3013 Register InputReg =
3014 getOrCreateConvergenceTokenVReg(*Bundle->Inputs[0].get());
3015 MIB.addUse(InputReg);
3016 }
3017
3018 return true;
3019}
3020
3021bool IRTranslatorImpl::translateKnownIntrinsic(const CallInst &CI,
3022 Intrinsic::ID ID,
3023 MachineIRBuilder &MIRBuilder) {
3024 if (auto *MI = dyn_cast<AnyMemIntrinsic>(&CI)) {
3025 if (ORE->enabled()) {
3026 if (MemoryOpRemark::canHandle(MI, *LibInfo)) {
3027 MemoryOpRemark R(*ORE, "gisel-ir-translator-memsize", *DL, *LibInfo);
3028 R.visit(MI);
3029 }
3030 }
3031 }
3032
3033 // If this is a simple intrinsic (that is, we just need to add a def of
3034 // a vreg, and uses for each arg operand, then translate it.
3035 if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
3036 return true;
3037
3038 switch (ID) {
3039 default:
3040 break;
3041 case Intrinsic::lifetime_start:
3042 case Intrinsic::lifetime_end: {
3043 // No stack colouring in O0, discard region information.
3044 if (MF->getTarget().getOptLevel() == CodeGenOptLevel::None ||
3045 MF->getFunction().hasOptNone())
3046 return true;
3047
3048 unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START
3049 : TargetOpcode::LIFETIME_END;
3050
3051 const AllocaInst *AI = dyn_cast<AllocaInst>(CI.getArgOperand(0));
3052 if (!AI || !AI->isStaticAlloca())
3053 return true;
3054
3055 MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI));
3056 return true;
3057 }
3058 case Intrinsic::fake_use: {
3060 for (const auto &Arg : CI.args())
3061 llvm::append_range(VRegs, getOrCreateVRegs(*Arg));
3062 MIRBuilder.buildInstr(TargetOpcode::FAKE_USE, {}, VRegs);
3063 MF->setHasFakeUses(true);
3064 return true;
3065 }
3066 case Intrinsic::dbg_declare: {
3067 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
3068 assert(DI.getVariable() && "Missing variable");
3069 translateDbgDeclareRecord(DI.getAddress(), DI.hasArgList(), DI.getVariable(),
3070 DI.getExpression(), DI.getDebugLoc(), MIRBuilder);
3071 return true;
3072 }
3073 case Intrinsic::dbg_label: {
3074 const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
3075 assert(DI.getLabel() && "Missing label");
3076
3078 MIRBuilder.getDebugLoc()) &&
3079 "Expected inlined-at fields to agree");
3080
3081 MIRBuilder.buildDbgLabel(DI.getLabel());
3082 return true;
3083 }
3084 case Intrinsic::vaend:
3085 // No target I know of cares about va_end. Certainly no in-tree target
3086 // does. Simplest intrinsic ever!
3087 return true;
3088 case Intrinsic::vastart: {
3089 Value *Ptr = CI.getArgOperand(0);
3090 unsigned ListSize = TLI->getVaListSizeInBits(*DL) / 8;
3091 Align Alignment = getKnownAlignment(Ptr, *DL);
3092
3093 MIRBuilder.buildInstr(TargetOpcode::G_VASTART, {}, {getOrCreateVReg(*Ptr)})
3094 .addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Ptr),
3096 ListSize, Alignment));
3097 return true;
3098 }
3099 case Intrinsic::dbg_assign:
3100 // A dbg.assign is a dbg.value with more information about stack locations,
3101 // typically produced during optimisation of variables with leaked
3102 // addresses. We can treat it like a normal dbg_value intrinsic here; to
3103 // benefit from the full analysis of stack/SSA locations, GlobalISel would
3104 // need to register for and use the AssignmentTrackingAnalysis pass.
3105 [[fallthrough]];
3106 case Intrinsic::dbg_value: {
3107 // This form of DBG_VALUE is target-independent.
3108 const DbgValueInst &DI = cast<DbgValueInst>(CI);
3109 translateDbgValueRecord(DI.getValue(), DI.hasArgList(), DI.getVariable(),
3110 DI.getExpression(), DI.getDebugLoc(), MIRBuilder);
3111 return true;
3112 }
3113 case Intrinsic::uadd_with_overflow:
3114 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
3115 case Intrinsic::sadd_with_overflow:
3116 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
3117 case Intrinsic::usub_with_overflow:
3118 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
3119 case Intrinsic::ssub_with_overflow:
3120 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
3121 case Intrinsic::umul_with_overflow:
3122 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
3123 case Intrinsic::smul_with_overflow:
3124 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
3125 case Intrinsic::uadd_sat:
3126 return translateBinaryOp(TargetOpcode::G_UADDSAT, CI, MIRBuilder);
3127 case Intrinsic::sadd_sat:
3128 return translateBinaryOp(TargetOpcode::G_SADDSAT, CI, MIRBuilder);
3129 case Intrinsic::usub_sat:
3130 return translateBinaryOp(TargetOpcode::G_USUBSAT, CI, MIRBuilder);
3131 case Intrinsic::ssub_sat:
3132 return translateBinaryOp(TargetOpcode::G_SSUBSAT, CI, MIRBuilder);
3133 case Intrinsic::ushl_sat:
3134 return translateBinaryOp(TargetOpcode::G_USHLSAT, CI, MIRBuilder);
3135 case Intrinsic::sshl_sat:
3136 return translateBinaryOp(TargetOpcode::G_SSHLSAT, CI, MIRBuilder);
3137 case Intrinsic::umin:
3138 return translateBinaryOp(TargetOpcode::G_UMIN, CI, MIRBuilder);
3139 case Intrinsic::umax:
3140 return translateBinaryOp(TargetOpcode::G_UMAX, CI, MIRBuilder);
3141 case Intrinsic::smin:
3142 return translateBinaryOp(TargetOpcode::G_SMIN, CI, MIRBuilder);
3143 case Intrinsic::smax:
3144 return translateBinaryOp(TargetOpcode::G_SMAX, CI, MIRBuilder);
3145 case Intrinsic::abs:
3146 // TODO: Preserve "int min is poison" arg in GMIR?
3147 return translateUnaryOp(TargetOpcode::G_ABS, CI, MIRBuilder);
3148 case Intrinsic::smul_fix:
3149 return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIX, CI, MIRBuilder);
3150 case Intrinsic::umul_fix:
3151 return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIX, CI, MIRBuilder);
3152 case Intrinsic::smul_fix_sat:
3153 return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIXSAT, CI, MIRBuilder);
3154 case Intrinsic::umul_fix_sat:
3155 return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIXSAT, CI, MIRBuilder);
3156 case Intrinsic::sdiv_fix:
3157 return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIX, CI, MIRBuilder);
3158 case Intrinsic::udiv_fix:
3159 return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIX, CI, MIRBuilder);
3160 case Intrinsic::sdiv_fix_sat:
3161 return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIXSAT, CI, MIRBuilder);
3162 case Intrinsic::udiv_fix_sat:
3163 return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIXSAT, CI, MIRBuilder);
3164 case Intrinsic::fmuladd: {
3165 Register Dst = getOrCreateVReg(CI);
3166 Register Op0 = getOrCreateVReg(*CI.getArgOperand(0));
3167 Register Op1 = getOrCreateVReg(*CI.getArgOperand(1));
3168 Register Op2 = getOrCreateVReg(*CI.getArgOperand(2));
3169 if (TLI->isFMAFasterThanFMulAndFAdd(*MF,
3170 TLI->getValueType(*DL, CI.getType()))) {
3171 // TODO: Revisit this to see if we should move this part of the
3172 // lowering to the combiner.
3173 MIRBuilder.buildFMA(Dst, Op0, Op1, Op2,
3175 } else {
3176 LLT Ty = getLLTForType(*CI.getType(), *DL);
3177 auto FMul = MIRBuilder.buildFMul(
3178 Ty, Op0, Op1, MachineInstr::copyFlagsFromInstruction(CI));
3179 MIRBuilder.buildFAdd(Dst, FMul, Op2,
3181 }
3182 return true;
3183 }
3184 case Intrinsic::frexp: {
3185 ArrayRef<Register> VRegs = getOrCreateVRegs(CI);
3186 MIRBuilder.buildFFrexp(VRegs[0], VRegs[1],
3187 getOrCreateVReg(*CI.getArgOperand(0)),
3189 return true;
3190 }
3191 case Intrinsic::modf: {
3192 ArrayRef<Register> VRegs = getOrCreateVRegs(CI);
3193 MIRBuilder.buildModf(VRegs[0], VRegs[1],
3194 getOrCreateVReg(*CI.getArgOperand(0)),
3196 return true;
3197 }
3198 case Intrinsic::sincos: {
3199 ArrayRef<Register> VRegs = getOrCreateVRegs(CI);
3200 MIRBuilder.buildFSincos(VRegs[0], VRegs[1],
3201 getOrCreateVReg(*CI.getArgOperand(0)),
3203 return true;
3204 }
3205 case Intrinsic::fptosi_sat:
3206 MIRBuilder.buildFPTOSI_SAT(getOrCreateVReg(CI),
3207 getOrCreateVReg(*CI.getArgOperand(0)));
3208 return true;
3209 case Intrinsic::fptoui_sat:
3210 MIRBuilder.buildFPTOUI_SAT(getOrCreateVReg(CI),
3211 getOrCreateVReg(*CI.getArgOperand(0)));
3212 return true;
3213 case Intrinsic::memcpy_inline:
3214 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMCPY_INLINE);
3215 case Intrinsic::memcpy:
3216 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMCPY);
3217 case Intrinsic::memmove:
3218 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMMOVE);
3219 case Intrinsic::memset:
3220 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMSET);
3221 case Intrinsic::memset_inline:
3222 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMSET_INLINE);
3223 case Intrinsic::eh_typeid_for: {
3224 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
3225 Register Reg = getOrCreateVReg(CI);
3226 unsigned TypeID = MF->getTypeIDFor(GV);
3227 MIRBuilder.buildConstant(Reg, TypeID);
3228 return true;
3229 }
3230 case Intrinsic::objectsize:
3231 llvm_unreachable("llvm.objectsize.* should have been lowered already");
3232
3233 case Intrinsic::is_constant:
3234 llvm_unreachable("llvm.is.constant.* should have been lowered already");
3235
3236 case Intrinsic::stackguard:
3237 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
3238 return true;
3239 case Intrinsic::stackprotector: {
3240 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
3241 Register GuardVal;
3242 if (TLI->useLoadStackGuardNode(*CI.getModule())) {
3243 GuardVal = MRI->createGenericVirtualRegister(PtrTy);
3244 getStackGuard(GuardVal, MIRBuilder);
3245 } else
3246 GuardVal = getOrCreateVReg(*CI.getArgOperand(0)); // The guard's value.
3247
3248 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
3249 int FI = getOrCreateFrameIndex(*Slot);
3250 MF->getFrameInfo().setStackProtectorIndex(FI);
3251
3252 MIRBuilder.buildStore(
3253 GuardVal, getOrCreateVReg(*Slot),
3254 *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
3257 PtrTy, Align(8)));
3258 return true;
3259 }
3260 case Intrinsic::stacksave: {
3261 MIRBuilder.buildInstr(TargetOpcode::G_STACKSAVE, {getOrCreateVReg(CI)}, {});
3262 return true;
3263 }
3264 case Intrinsic::stackrestore: {
3265 MIRBuilder.buildInstr(TargetOpcode::G_STACKRESTORE, {},
3266 {getOrCreateVReg(*CI.getArgOperand(0))});
3267 return true;
3268 }
3269 case Intrinsic::cttz:
3270 case Intrinsic::ctlz: {
3271 ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
3272 bool isTrailing = ID == Intrinsic::cttz;
3273 unsigned Opcode = isTrailing ? Cst->isZero()
3274 ? TargetOpcode::G_CTTZ
3275 : TargetOpcode::G_CTTZ_ZERO_POISON
3276 : Cst->isZero() ? TargetOpcode::G_CTLZ
3277 : TargetOpcode::G_CTLZ_ZERO_POISON;
3278 MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(CI)},
3279 {getOrCreateVReg(*CI.getArgOperand(0))});
3280 return true;
3281 }
3282 case Intrinsic::invariant_start: {
3283 MIRBuilder.buildUndef(getOrCreateVReg(CI));
3284 return true;
3285 }
3286 case Intrinsic::invariant_end:
3287 return true;
3288 case Intrinsic::expect:
3289 case Intrinsic::expect_with_probability:
3290 case Intrinsic::annotation:
3291 case Intrinsic::ptr_annotation:
3292 case Intrinsic::launder_invariant_group:
3293 case Intrinsic::threadlocal_address: {
3294 // Drop the intrinsic, but forward the value.
3295 MIRBuilder.buildCopy(getOrCreateVReg(CI),
3296 getOrCreateVReg(*CI.getArgOperand(0)));
3297 return true;
3298 }
3299 case Intrinsic::assume:
3300 case Intrinsic::experimental_noalias_scope_decl:
3301 case Intrinsic::var_annotation:
3302 case Intrinsic::sideeffect:
3303 // Discard annotate attributes, assumptions, and artificial side-effects.
3304 return true;
3305 case Intrinsic::read_volatile_register:
3306 case Intrinsic::read_register: {
3307 Value *Arg = CI.getArgOperand(0);
3308 MIRBuilder
3309 .buildInstr(TargetOpcode::G_READ_REGISTER, {getOrCreateVReg(CI)}, {})
3310 .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()));
3311 return true;
3312 }
3313 case Intrinsic::write_register: {
3314 Value *Arg = CI.getArgOperand(0);
3315 MIRBuilder.buildInstr(TargetOpcode::G_WRITE_REGISTER)
3316 .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()))
3317 .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
3318 return true;
3319 }
3320 case Intrinsic::localescape: {
3321 MachineBasicBlock &EntryMBB = MF->front();
3322 StringRef EscapedName = GlobalValue::dropLLVMManglingEscape(MF->getName());
3323
3324 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
3325 // is the same on all targets.
3326 for (unsigned Idx = 0, E = CI.arg_size(); Idx < E; ++Idx) {
3327 Value *Arg = CI.getArgOperand(Idx)->stripPointerCasts();
3328 if (isa<ConstantPointerNull>(Arg))
3329 continue; // Skip null pointers. They represent a hole in index space.
3330
3331 int FI = getOrCreateFrameIndex(*cast<AllocaInst>(Arg));
3332 MCSymbol *FrameAllocSym =
3333 MF->getContext().getOrCreateFrameAllocSymbol(EscapedName, Idx);
3334
3335 // This should be inserted at the start of the entry block.
3336 auto LocalEscape =
3337 MIRBuilder.buildInstrNoInsert(TargetOpcode::LOCAL_ESCAPE)
3338 .addSym(FrameAllocSym)
3339 .addFrameIndex(FI);
3340
3341 EntryMBB.insert(EntryMBB.begin(), LocalEscape);
3342 }
3343
3344 return true;
3345 }
3346 case Intrinsic::vector_reduce_fadd:
3347 case Intrinsic::vector_reduce_fmul: {
3348 // Need to check for the reassoc flag to decide whether we want a
3349 // sequential reduction opcode or not.
3350 Register Dst = getOrCreateVReg(CI);
3351 Register ScalarSrc = getOrCreateVReg(*CI.getArgOperand(0));
3352 Register VecSrc = getOrCreateVReg(*CI.getArgOperand(1));
3353 unsigned Opc = 0;
3354 if (!CI.hasAllowReassoc()) {
3355 // The sequential ordering case.
3356 Opc = ID == Intrinsic::vector_reduce_fadd
3357 ? TargetOpcode::G_VECREDUCE_SEQ_FADD
3358 : TargetOpcode::G_VECREDUCE_SEQ_FMUL;
3359 if (!MRI->getType(VecSrc).isVector())
3360 Opc = ID == Intrinsic::vector_reduce_fadd ? TargetOpcode::G_FADD
3361 : TargetOpcode::G_FMUL;
3362 MIRBuilder.buildInstr(Opc, {Dst}, {ScalarSrc, VecSrc},
3364 return true;
3365 }
3366 // We split the operation into a separate G_FADD/G_FMUL + the reduce,
3367 // since the associativity doesn't matter.
3368 unsigned ScalarOpc;
3369 if (ID == Intrinsic::vector_reduce_fadd) {
3370 Opc = TargetOpcode::G_VECREDUCE_FADD;
3371 ScalarOpc = TargetOpcode::G_FADD;
3372 } else {
3373 Opc = TargetOpcode::G_VECREDUCE_FMUL;
3374 ScalarOpc = TargetOpcode::G_FMUL;
3375 }
3376 LLT DstTy = MRI->getType(Dst);
3377 auto Rdx = MIRBuilder.buildInstr(
3378 Opc, {DstTy}, {VecSrc}, MachineInstr::copyFlagsFromInstruction(CI));
3379 MIRBuilder.buildInstr(ScalarOpc, {Dst}, {ScalarSrc, Rdx},
3381
3382 return true;
3383 }
3384 case Intrinsic::trap:
3385 return translateTrap(CI, MIRBuilder, TargetOpcode::G_TRAP);
3386 case Intrinsic::debugtrap:
3387 return translateTrap(CI, MIRBuilder, TargetOpcode::G_DEBUGTRAP);
3388 case Intrinsic::ubsantrap:
3389 return translateTrap(CI, MIRBuilder, TargetOpcode::G_UBSANTRAP);
3390 case Intrinsic::allow_runtime_check:
3391 case Intrinsic::allow_ubsan_check:
3392 MIRBuilder.buildCopy(getOrCreateVReg(CI),
3393 getOrCreateVReg(*ConstantInt::getTrue(CI.getType())));
3394 return true;
3395 case Intrinsic::amdgcn_cs_chain:
3396 case Intrinsic::amdgcn_call_whole_wave:
3397 return translateCallBase(CI, MIRBuilder);
3398 case Intrinsic::fptrunc_round: {
3400
3401 // Convert the metadata argument to a constant integer
3402 Metadata *MD = cast<MetadataAsValue>(CI.getArgOperand(1))->getMetadata();
3403 std::optional<RoundingMode> RoundMode =
3404 convertStrToRoundingMode(cast<MDString>(MD)->getString());
3405
3406 // Add the Rounding mode as an integer
3407 MIRBuilder
3408 .buildInstr(TargetOpcode::G_INTRINSIC_FPTRUNC_ROUND,
3409 {getOrCreateVReg(CI)},
3410 {getOrCreateVReg(*CI.getArgOperand(0))}, Flags)
3411 .addImm((int)*RoundMode);
3412
3413 return true;
3414 }
3415 case Intrinsic::is_fpclass: {
3416 Value *FpValue = CI.getOperand(0);
3417 ConstantInt *TestMaskValue = cast<ConstantInt>(CI.getOperand(1));
3418
3419 MIRBuilder
3420 .buildInstr(TargetOpcode::G_IS_FPCLASS, {getOrCreateVReg(CI)},
3421 {getOrCreateVReg(*FpValue)})
3422 .addImm(TestMaskValue->getZExtValue());
3423
3424 return true;
3425 }
3426 case Intrinsic::set_fpenv: {
3427 Value *FPEnv = CI.getOperand(0);
3428 MIRBuilder.buildSetFPEnv(getOrCreateVReg(*FPEnv));
3429 return true;
3430 }
3431 case Intrinsic::reset_fpenv:
3432 MIRBuilder.buildResetFPEnv();
3433 return true;
3434 case Intrinsic::set_fpmode: {
3435 Value *FPState = CI.getOperand(0);
3436 MIRBuilder.buildSetFPMode(getOrCreateVReg(*FPState));
3437 return true;
3438 }
3439 case Intrinsic::reset_fpmode:
3440 MIRBuilder.buildResetFPMode();
3441 return true;
3442 case Intrinsic::get_rounding:
3443 MIRBuilder.buildGetRounding(getOrCreateVReg(CI));
3444 return true;
3445 case Intrinsic::set_rounding:
3446 MIRBuilder.buildSetRounding(getOrCreateVReg(*CI.getOperand(0)));
3447 return true;
3448 case Intrinsic::vscale: {
3449 MIRBuilder.buildVScale(getOrCreateVReg(CI), 1);
3450 return true;
3451 }
3452 case Intrinsic::scmp:
3453 MIRBuilder.buildSCmp(getOrCreateVReg(CI),
3454 getOrCreateVReg(*CI.getOperand(0)),
3455 getOrCreateVReg(*CI.getOperand(1)));
3456 return true;
3457 case Intrinsic::ucmp:
3458 MIRBuilder.buildUCmp(getOrCreateVReg(CI),
3459 getOrCreateVReg(*CI.getOperand(0)),
3460 getOrCreateVReg(*CI.getOperand(1)));
3461 return true;
3462 case Intrinsic::vector_extract:
3463 return translateExtractVector(CI, MIRBuilder);
3464 case Intrinsic::vector_insert:
3465 return translateInsertVector(CI, MIRBuilder);
3466 case Intrinsic::stepvector: {
3467 MIRBuilder.buildStepVector(getOrCreateVReg(CI), 1);
3468 return true;
3469 }
3470 case Intrinsic::prefetch: {
3471 Value *Addr = CI.getOperand(0);
3472 unsigned RW = cast<ConstantInt>(CI.getOperand(1))->getZExtValue();
3473 unsigned Locality = cast<ConstantInt>(CI.getOperand(2))->getZExtValue();
3474 unsigned CacheType = cast<ConstantInt>(CI.getOperand(3))->getZExtValue();
3475
3477 auto &MMO = *MF->getMachineMemOperand(MachinePointerInfo(Addr), Flags,
3478 LLT(), Align());
3479
3480 MIRBuilder.buildPrefetch(getOrCreateVReg(*Addr), RW, Locality, CacheType,
3481 MMO);
3482
3483 return true;
3484 }
3485
3486 case Intrinsic::speculative_load: {
3487 // Only the pointer operand is needed at codegen; the remaining arguments
3488 // carry IR-level semantics only.
3489 const Value *Ptr = CI.getArgOperand(0);
3490 Register Dst = getOrCreateVReg(CI);
3492 Flags |= TLI->getTargetMMOFlags(CI);
3493 if (CI.hasMetadata(LLVMContext::MD_nontemporal))
3495 if (CI.hasMetadata(LLVMContext::MD_invariant_load))
3497 auto *MMO = MF->getMachineMemOperand(
3498 MachinePointerInfo(Ptr), Flags, MRI->getType(Dst),
3499 CI.getParamAlign(0).valueOrOne(), MMOMetadata(CI.getAAMetadata()));
3500 MIRBuilder.buildLoad(Dst, getOrCreateVReg(*Ptr), *MMO);
3501 return true;
3502 }
3503
3504 case Intrinsic::vector_interleave2:
3505 case Intrinsic::vector_deinterleave2: {
3506 // Both intrinsics have at least one operand.
3507 Value *Op0 = CI.getOperand(0);
3508 LLT ResTy = getLLTForType(*Op0->getType(), MIRBuilder.getDataLayout());
3509 if (!ResTy.isFixedVector())
3510 return false;
3511
3512 if (CI.getIntrinsicID() == Intrinsic::vector_interleave2)
3513 return translateVectorInterleave2Intrinsic(CI, MIRBuilder);
3514
3515 return translateVectorDeinterleave2Intrinsic(CI, MIRBuilder);
3516 }
3517
3518#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
3519 case Intrinsic::INTRINSIC:
3520#include "llvm/IR/ConstrainedOps.def"
3521 return translateConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(CI),
3522 MIRBuilder);
3523 case Intrinsic::experimental_convergence_anchor:
3524 case Intrinsic::experimental_convergence_entry:
3525 case Intrinsic::experimental_convergence_loop:
3526 return translateConvergenceControlIntrinsic(CI, ID, MIRBuilder);
3527 case Intrinsic::reloc_none: {
3528 Metadata *MD = cast<MetadataAsValue>(CI.getArgOperand(0))->getMetadata();
3529 StringRef SymbolName = cast<MDString>(MD)->getString();
3530 MIRBuilder.buildInstr(TargetOpcode::RELOC_NONE)
3532 return true;
3533 }
3534 }
3535 return false;
3536}
3537
3538bool IRTranslatorImpl::translateInlineAsm(const CallBase &CB,
3539 MachineIRBuilder &MIRBuilder) {
3540 if (!mayTranslateUserTypes(CB))
3541 return false;
3542
3543 const InlineAsmLowering *ALI = MF->getSubtarget().getInlineAsmLowering();
3544
3545 if (!ALI) {
3546 LLVM_DEBUG(
3547 dbgs() << "Inline asm lowering is not supported for this target yet\n");
3548 return false;
3549 }
3550
3551 return ALI->lowerInlineAsm(
3552 MIRBuilder, CB, [&](const Value &Val) { return getOrCreateVRegs(Val); });
3553}
3554
3555bool IRTranslatorImpl::translateCallBase(const CallBase &CB,
3556 MachineIRBuilder &MIRBuilder) {
3557 ArrayRef<Register> Res = getOrCreateVRegs(CB);
3558
3560 Register SwiftInVReg = 0;
3561 Register SwiftErrorVReg = 0;
3562 for (const auto &Arg : CB.args()) {
3563 if (CLI->supportSwiftError() && isSwiftError(Arg)) {
3564 assert(SwiftInVReg == 0 && "Expected only one swift error argument");
3565 LLT Ty = getLLTForType(*Arg->getType(), *DL);
3566 SwiftInVReg = MRI->createGenericVirtualRegister(Ty);
3567 MIRBuilder.buildCopy(SwiftInVReg, SwiftError.getOrCreateVRegUseAt(
3568 &CB, &MIRBuilder.getMBB(), Arg));
3569 Args.emplace_back(ArrayRef(SwiftInVReg));
3570 SwiftErrorVReg =
3571 SwiftError.getOrCreateVRegDefAt(&CB, &MIRBuilder.getMBB(), Arg);
3572 continue;
3573 }
3574 Args.push_back(getOrCreateVRegs(*Arg));
3575 }
3576
3577 if (auto *CI = dyn_cast<CallInst>(&CB)) {
3578 if (ORE->enabled()) {
3579 if (MemoryOpRemark::canHandle(CI, *LibInfo)) {
3580 MemoryOpRemark R(*ORE, "gisel-ir-translator-memsize", *DL, *LibInfo);
3581 R.visit(CI);
3582 }
3583 }
3584 }
3585
3586 std::optional<CallLowering::PtrAuthInfo> PAI;
3587 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_ptrauth)) {
3588 // Functions should never be ptrauth-called directly.
3589 assert(!CB.getCalledFunction() && "invalid direct ptrauth call");
3590
3591 const Value *Key = Bundle->Inputs[0];
3592 const Value *Discriminator = Bundle->Inputs[1];
3593
3594 // Look through ptrauth constants to try to eliminate the matching bundle
3595 // and turn this into a direct call with no ptrauth.
3596 // CallLowering will use the raw pointer if it doesn't find the PAI.
3597 const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CB.getCalledOperand());
3598 if (!CalleeCPA || !isa<Function>(CalleeCPA->getPointer()) ||
3599 !CalleeCPA->isKnownCompatibleWith(Key, Discriminator, *DL)) {
3600 // If we can't make it direct, package the bundle into PAI.
3601 Register DiscReg = getOrCreateVReg(*Discriminator);
3602 PAI = CallLowering::PtrAuthInfo{cast<ConstantInt>(Key)->getZExtValue(),
3603 DiscReg};
3604 }
3605 }
3606
3607 Register ConvergenceCtrlToken = 0;
3608 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
3609 const auto &Token = *Bundle->Inputs[0].get();
3610 ConvergenceCtrlToken = getOrCreateConvergenceTokenVReg(Token);
3611 }
3612
3613 // We don't set HasCalls on MFI here yet because call lowering may decide to
3614 // optimize into tail calls. Instead, we defer that to selection where a final
3615 // scan is done to check if any instructions are calls.
3616 bool Success = CLI->lowerCall(
3617 MIRBuilder, CB, Res, Args, SwiftErrorVReg, PAI, ConvergenceCtrlToken,
3618 [&]() { return getOrCreateVReg(*CB.getCalledOperand()); });
3619
3620 // Check if we just inserted a tail call.
3621 if (Success) {
3622 assert(!HasTailCall && "Can't tail call return twice from block?");
3623 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
3624 HasTailCall = TII->isTailCall(*std::prev(MIRBuilder.getInsertPt()));
3625 }
3626
3627 return Success;
3628}
3629
3630bool IRTranslatorImpl::translateCall(const User &U,
3631 MachineIRBuilder &MIRBuilder) {
3632 if (!mayTranslateUserTypes(U))
3633 return false;
3634
3635 const CallInst &CI = cast<CallInst>(U);
3636 const Function *F = CI.getCalledFunction();
3637
3638 // FIXME: support Windows dllimport function calls and calls through
3639 // weak symbols.
3640 if (F && (F->hasDLLImportStorageClass() ||
3641 (MF->getTarget().getTargetTriple().isOSWindows() &&
3642 F->hasExternalWeakLinkage())))
3643 return false;
3644
3645 // FIXME: support control flow guard targets.
3647 return false;
3648
3649 // FIXME: support statepoints and related.
3651 return false;
3652
3653 if (CI.isInlineAsm())
3654 return translateInlineAsm(CI, MIRBuilder);
3655
3656 Intrinsic::ID ID = F ? F->getIntrinsicID() : Intrinsic::not_intrinsic;
3657 if (!F || ID == Intrinsic::not_intrinsic) {
3658 if (translateCallBase(CI, MIRBuilder)) {
3659 diagnoseDontCall(CI);
3660 return true;
3661 }
3662 return false;
3663 }
3664
3665 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
3666
3667 if (!MF->getSubtarget().isIntrinsicSupported(ID)) {
3668 const Function &Fn = MF->getFunction();
3669 Fn.getContext().diagnose(
3670 DiagnosticInfoUnsupportedTargetIntrinsic(Fn, ID, CI.getDebugLoc()));
3671 }
3672
3673 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
3674 return true;
3675
3677 TLI->getTgtMemIntrinsic(Infos, CI, *MF, ID);
3678
3679 return translateIntrinsic(CI, ID, MIRBuilder, Infos);
3680}
3681
3682/// Translate a call or callbr to an intrinsic.
3683bool IRTranslatorImpl::translateIntrinsic(
3684 const CallBase &CB, Intrinsic::ID ID, MachineIRBuilder &MIRBuilder,
3685 ArrayRef<TargetLowering::IntrinsicInfo> TgtMemIntrinsicInfos) {
3686 if (!MF->getSubtarget().isIntrinsicSupported(ID)) {
3687 const Function &F = MF->getFunction();
3688 F.getContext().diagnose(
3689 DiagnosticInfoUnsupportedTargetIntrinsic(F, ID, CB.getDebugLoc()));
3690 }
3691
3692 ArrayRef<Register> ResultRegs;
3693 if (!CB.getType()->isVoidTy())
3694 ResultRegs = getOrCreateVRegs(CB);
3695
3696 // Ignore the callsite attributes. Backend code is most likely not expecting
3697 // an intrinsic to sometimes have side effects and sometimes not.
3698 MachineInstrBuilder MIB = MIRBuilder.buildIntrinsic(ID, ResultRegs);
3699 if (isa<FPMathOperator>(CB))
3700 MIB->copyIRFlags(CB);
3701
3702 for (const auto &Arg : enumerate(CB.args())) {
3703 // If this is required to be an immediate, don't materialize it in a
3704 // register.
3705 if (CB.paramHasAttr(Arg.index(), Attribute::ImmArg)) {
3706 if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg.value())) {
3707 // imm arguments are more convenient than cimm (and realistically
3708 // probably sufficient), so use them.
3709 assert(CI->getBitWidth() <= 64 &&
3710 "large intrinsic immediates not handled");
3711 MIB.addImm(CI->getSExtValue());
3712 } else {
3713 MIB.addFPImm(cast<ConstantFP>(Arg.value()));
3714 }
3715 } else if (auto *MDVal = dyn_cast<MetadataAsValue>(Arg.value())) {
3716 auto *MD = MDVal->getMetadata();
3717 auto *MDN = dyn_cast<MDNode>(MD);
3718 if (!MDN) {
3719 if (auto *ConstMD = dyn_cast<ConstantAsMetadata>(MD))
3720 MDN = MDNode::get(MF->getFunction().getContext(), ConstMD);
3721 else // This was probably an MDString.
3722 return false;
3723 }
3724 MIB.addMetadata(MDN);
3725 } else {
3726 ArrayRef<Register> VRegs = getOrCreateVRegs(*Arg.value());
3727 if (VRegs.size() > 1)
3728 return false;
3729 MIB.addUse(VRegs[0]);
3730 }
3731 }
3732
3733 // Add MachineMemOperands for each memory access described by the target.
3734 for (const auto &Info : TgtMemIntrinsicInfos) {
3735 Align Alignment = Info.align.value_or(
3736 DL->getABITypeAlign(Info.memVT.getTypeForEVT(CB.getContext())));
3737 LLT MemTy = Info.memVT.isSimple()
3738 ? getLLTForMVT(Info.memVT.getSimpleVT())
3739 : LLT::scalar(Info.memVT.getStoreSizeInBits());
3740
3741 // TODO: We currently just fallback to address space 0 if
3742 // getTgtMemIntrinsic didn't yield anything useful.
3743 MachinePointerInfo MPI;
3744 if (Info.ptrVal) {
3745 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
3746 } else if (Info.fallbackAddressSpace) {
3747 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
3748 }
3749 MIB.addMemOperand(MF->getMachineMemOperand(
3750 MPI, Info.flags, MemTy, Alignment, CB.getAAMetadata(), Info.ssid,
3751 Info.order, Info.failureOrder));
3752 }
3753
3754 if (CB.isConvergent()) {
3755 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
3756 auto *Token = Bundle->Inputs[0].get();
3757 Register TokenReg = getOrCreateVReg(*Token);
3758 MIB.addUse(TokenReg, RegState::Implicit);
3759 }
3760 }
3761
3763 MIB->setDeactivationSymbol(*MF, Bundle->Inputs[0].get());
3764
3765 return true;
3766}
3767
3768bool IRTranslatorImpl::findUnwindDestinations(
3769 const BasicBlock *EHPadBB, BranchProbability Prob,
3770 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
3771 &UnwindDests) {
3773 EHPadBB->getParent()->getFunction().getPersonalityFn());
3774 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
3775 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
3776 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
3777 bool IsWasmD = Personality == EHPersonality::Wasm_D;
3778 bool IsSEH = isAsynchronousEHPersonality(Personality);
3779
3780 if (IsWasmCXX || IsWasmD) {
3781 // Ignore this for now.
3782 return false;
3783 }
3784
3785 while (EHPadBB) {
3787 BasicBlock *NewEHPadBB = nullptr;
3788 if (isa<LandingPadInst>(Pad)) {
3789 // Stop on landingpads. They are not funclets.
3790 UnwindDests.emplace_back(&getMBB(*EHPadBB), Prob);
3791 break;
3792 }
3793 if (isa<CleanupPadInst>(Pad)) {
3794 // Stop on cleanup pads. Cleanups are always funclet entries for all known
3795 // personalities.
3796 UnwindDests.emplace_back(&getMBB(*EHPadBB), Prob);
3797 UnwindDests.back().first->setIsEHScopeEntry();
3798 UnwindDests.back().first->setIsEHFuncletEntry();
3799 break;
3800 }
3801 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
3802 // Add the catchpad handlers to the possible destinations.
3803 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
3804 UnwindDests.emplace_back(&getMBB(*CatchPadBB), Prob);
3805 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
3806 if (IsMSVCCXX || IsCoreCLR)
3807 UnwindDests.back().first->setIsEHFuncletEntry();
3808 if (!IsSEH)
3809 UnwindDests.back().first->setIsEHScopeEntry();
3810 }
3811 NewEHPadBB = CatchSwitch->getUnwindDest();
3812 } else {
3813 continue;
3814 }
3815
3816 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3817 if (BPI && NewEHPadBB)
3818 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
3819 EHPadBB = NewEHPadBB;
3820 }
3821 return true;
3822}
3823
3824bool IRTranslatorImpl::translateInvoke(const User &U,
3825 MachineIRBuilder &MIRBuilder) {
3826 const InvokeInst &I = cast<InvokeInst>(U);
3827 MCContext &Context = MF->getContext();
3828
3829 const BasicBlock *ReturnBB = I.getSuccessor(0);
3830 const BasicBlock *EHPadBB = I.getSuccessor(1);
3831
3832 const Function *Fn = I.getCalledFunction();
3833
3834 // FIXME: support invoking patchpoint and statepoint intrinsics.
3835 if (Fn && Fn->isIntrinsic())
3836 return false;
3837
3838 // FIXME: support whatever these are.
3839 if (I.hasDeoptState())
3840 return false;
3841
3842 // FIXME: support control flow guard targets.
3843 if (I.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget))
3844 return false;
3845
3846 // FIXME: support Windows exception handling.
3847 if (!isa<LandingPadInst>(EHPadBB->getFirstNonPHIIt()))
3848 return false;
3849
3850 // FIXME: support Windows dllimport function calls and calls through
3851 // weak symbols.
3852 if (Fn && (Fn->hasDLLImportStorageClass() ||
3853 (MF->getTarget().getTargetTriple().isOSWindows() &&
3854 Fn->hasExternalWeakLinkage())))
3855 return false;
3856
3857 bool LowerInlineAsm = I.isInlineAsm();
3858 bool NeedEHLabel = true;
3859
3860 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
3861 // the region covered by the try.
3862 MCSymbol *BeginSymbol = nullptr;
3863 if (NeedEHLabel) {
3864 MIRBuilder.buildInstr(TargetOpcode::G_INVOKE_REGION_START);
3865 BeginSymbol = Context.createTempSymbol();
3866 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
3867 }
3868
3869 if (LowerInlineAsm) {
3870 if (!translateInlineAsm(I, MIRBuilder))
3871 return false;
3872 } else if (!translateCallBase(I, MIRBuilder))
3873 return false;
3874
3875 MCSymbol *EndSymbol = nullptr;
3876 if (NeedEHLabel) {
3877 EndSymbol = Context.createTempSymbol();
3878 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
3879 }
3880
3882 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3883 MachineBasicBlock *InvokeMBB = &MIRBuilder.getMBB();
3884 BranchProbability EHPadBBProb =
3885 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3887
3888 if (!findUnwindDestinations(EHPadBB, EHPadBBProb, UnwindDests))
3889 return false;
3890
3891 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
3892 &ReturnMBB = getMBB(*ReturnBB);
3893 // Update successor info.
3894 addSuccessorWithProb(InvokeMBB, &ReturnMBB);
3895 for (auto &UnwindDest : UnwindDests) {
3896 UnwindDest.first->setIsEHPad();
3897 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3898 }
3899 InvokeMBB->normalizeSuccProbs();
3900
3901 if (NeedEHLabel) {
3902 assert(BeginSymbol && "Expected a begin symbol!");
3903 assert(EndSymbol && "Expected an end symbol!");
3904 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
3905 }
3906
3907 MIRBuilder.buildBr(ReturnMBB);
3908 return true;
3909}
3910
3911/// The intrinsics currently supported by callbr are implicit control flow
3912/// intrinsics such as amdgcn.kill.
3913bool IRTranslatorImpl::translateCallBr(const User &U,
3914 MachineIRBuilder &MIRBuilder) {
3915 if (!mayTranslateUserTypes(U))
3916 return false; // see translateCall
3917
3918 const CallBrInst &I = cast<CallBrInst>(U);
3919 MachineBasicBlock *CallBrMBB = &MIRBuilder.getMBB();
3920
3921 Intrinsic::ID IID = I.getIntrinsicID();
3922 if (I.isInlineAsm()) {
3923 // FIXME: inline asm is not yet supported for callbr in GlobalISel. As soon
3924 // as we add support, we need to handle the indirect asm targets, see
3925 // SelectionDAGBuilder::visitCallBr().
3926 return false;
3927 }
3928 if (!translateIntrinsic(I, IID, MIRBuilder))
3929 return false;
3930
3931 // Retrieve successors.
3932 SmallPtrSet<BasicBlock *, 8> Dests = {I.getDefaultDest()};
3933 MachineBasicBlock *Return = &getMBB(*I.getDefaultDest());
3934
3935 // Update successor info.
3936 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3937
3938 // Add indirect targets as successors. For intrinsic callbr, these represent
3939 // implicit control flow (e.g., the "kill" path for amdgcn.kill). We mark them
3940 // with setIsInlineAsmBrIndirectTarget so the machine verifier accepts them as
3941 // valid successors, even though they're not from inline asm.
3942 for (BasicBlock *Dest : I.getIndirectDests()) {
3943 MachineBasicBlock &Target = getMBB(*Dest);
3944 Target.setIsInlineAsmBrIndirectTarget();
3945 Target.setLabelMustBeEmitted();
3946 // Don't add duplicate machine successors.
3947 if (Dests.insert(Dest).second)
3948 addSuccessorWithProb(CallBrMBB, &Target, BranchProbability::getZero());
3949 }
3950
3951 CallBrMBB->normalizeSuccProbs();
3952
3953 // Drop into default successor.
3954 MIRBuilder.buildBr(*Return);
3955
3956 return true;
3957}
3958
3959bool IRTranslatorImpl::translateLandingPad(const User &U,
3960 MachineIRBuilder &MIRBuilder) {
3961 const LandingPadInst &LP = cast<LandingPadInst>(U);
3962
3963 MachineBasicBlock &MBB = MIRBuilder.getMBB();
3964
3965 MBB.setIsEHPad();
3966
3967 // If there aren't registers to copy the values into (e.g., during SjLj
3968 // exceptions), then don't bother.
3969 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
3970 if (TLI->getExceptionPointerRegister(FuncInfo.ExceptionModel,
3971 PersonalityFn) == 0 &&
3972 TLI->getExceptionSelectorRegister(FuncInfo.ExceptionModel,
3973 PersonalityFn) == 0)
3974 return true;
3975
3976 // If landingpad's return type is token type, we don't create DAG nodes
3977 // for its exception pointer and selector value. The extraction of exception
3978 // pointer or selector value from token type landingpads is not currently
3979 // supported.
3980 if (LP.getType()->isTokenTy())
3981 return true;
3982
3984 return false;
3985
3986 // Add a label to mark the beginning of the landing pad. Deletion of the
3987 // landing pad can thus be detected via the MachineModuleInfo.
3988 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
3989 .addSym(MF->addLandingPad(&MBB));
3990
3991 // If the unwinder does not preserve all registers, ensure that the
3992 // function marks the clobbered registers as used.
3993 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
3994 if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
3995 MF->getRegInfo().addPhysRegsUsedFromRegMask(RegMask);
3996
3997 LLT Ty = getLLTForType(*LP.getType(), *DL);
3998 Register Undef = MRI->createGenericVirtualRegister(Ty);
3999 MIRBuilder.buildUndef(Undef);
4000
4002 for (Type *Ty : cast<StructType>(LP.getType())->elements())
4003 Tys.push_back(getLLTForType(*Ty, *DL));
4004 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
4005
4006 // Mark exception register as live in.
4007 Register ExceptionReg =
4008 TLI->getExceptionPointerRegister(FuncInfo.ExceptionModel, PersonalityFn);
4009 if (!ExceptionReg)
4010 return false;
4011
4012 MBB.addLiveIn(ExceptionReg);
4013 ArrayRef<Register> ResRegs = getOrCreateVRegs(LP);
4014 MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
4015
4016 Register SelectorReg =
4017 TLI->getExceptionSelectorRegister(FuncInfo.ExceptionModel, PersonalityFn);
4018 if (!SelectorReg)
4019 return false;
4020
4021 MBB.addLiveIn(SelectorReg);
4022 Register PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
4023 MIRBuilder.buildCopy(PtrVReg, SelectorReg);
4024 MIRBuilder.buildCast(ResRegs[1], PtrVReg);
4025
4026 return true;
4027}
4028
4029bool IRTranslatorImpl::translateAlloca(const User &U,
4030 MachineIRBuilder &MIRBuilder) {
4031 auto &AI = cast<AllocaInst>(U);
4032
4033 if (AI.isSwiftError())
4034 return true;
4035
4036 if (AI.isStaticAlloca()) {
4037 Register Res = getOrCreateVReg(AI);
4038 int FI = getOrCreateFrameIndex(AI);
4039 MIRBuilder.buildFrameIndex(Res, FI);
4040 return true;
4041 }
4042
4043 // FIXME: support stack probing for Windows.
4044 if (MF->getTarget().getTargetTriple().isOSWindows())
4045 return false;
4046
4047 // Now we're in the harder dynamic case.
4048 Register NumElts = getOrCreateVReg(*AI.getArraySize());
4049 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
4050 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
4051 if (MRI->getType(NumElts) != IntPtrTy) {
4052 Register ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
4053 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
4054 NumElts = ExtElts;
4055 }
4056
4057 TypeSize TySize = AI.getAllocationBaseSize(*DL);
4058
4059 Register AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
4060 Register TySizeReg;
4061 if (TySize.isScalable()) {
4062 // For scalable types, use vscale * min_value
4063 TySizeReg = MRI->createGenericVirtualRegister(IntPtrTy);
4064 MIRBuilder.buildVScale(TySizeReg, TySize.getKnownMinValue());
4065 } else {
4066 // For fixed types, use a constant
4067 TySizeReg =
4068 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, TySize.getFixedValue()));
4069 }
4070 MIRBuilder.buildMul(AllocSize, NumElts, TySizeReg);
4071
4072 // Round the size of the allocation up to the stack alignment size
4073 // by add SA-1 to the size. This doesn't overflow because we're computing
4074 // an address inside an alloca.
4075 Align StackAlign = MF->getSubtarget().getFrameLowering()->getStackAlign();
4076 auto SAMinusOne = MIRBuilder.buildConstant(IntPtrTy, StackAlign.value() - 1);
4077 auto AllocAdd = MIRBuilder.buildAdd(IntPtrTy, AllocSize, SAMinusOne,
4079 auto AlignCst =
4080 MIRBuilder.buildConstant(IntPtrTy, ~(uint64_t)(StackAlign.value() - 1));
4081 auto AlignedAlloc = MIRBuilder.buildAnd(IntPtrTy, AllocAdd, AlignCst);
4082
4083 Align Alignment = AI.getAlign();
4084 if (Alignment <= StackAlign)
4085 Alignment = Align(1);
4086 MIRBuilder.buildDynStackAlloc(getOrCreateVReg(AI), AlignedAlloc, Alignment);
4087
4088 MF->getFrameInfo().CreateVariableSizedObject(Alignment, &AI);
4089 assert(MF->getFrameInfo().hasVarSizedObjects());
4090 return true;
4091}
4092
4093bool IRTranslatorImpl::translateVAArg(const User &U,
4094 MachineIRBuilder &MIRBuilder) {
4095 // FIXME: We may need more info about the type. Because of how LLT works,
4096 // we're completely discarding the i64/double distinction here (amongst
4097 // others). Fortunately the ABIs I know of where that matters don't use va_arg
4098 // anyway but that's not guaranteed.
4099 MIRBuilder.buildInstr(TargetOpcode::G_VAARG, {getOrCreateVReg(U)},
4100 {getOrCreateVReg(*U.getOperand(0)),
4101 DL->getABITypeAlign(U.getType()).value()});
4102 return true;
4103}
4104
4105bool IRTranslatorImpl::translateUnreachable(const User &U,
4106 MachineIRBuilder &MIRBuilder) {
4107 auto &UI = cast<UnreachableInst>(U);
4108 if (!UI.shouldLowerToTrap(MF->getTarget().Options.TrapUnreachable,
4109 MF->getTarget().Options.NoTrapAfterNoreturn))
4110 return true;
4111
4112 MIRBuilder.buildTrap();
4113 return true;
4114}
4115
4116bool IRTranslatorImpl::translateInsertElement(const User &U,
4117 MachineIRBuilder &MIRBuilder) {
4118 // If it is a <1 x Ty> vector, use the scalar as it is
4119 // not a legal vector type in LLT.
4120 if (auto *FVT = dyn_cast<FixedVectorType>(U.getType());
4121 FVT && FVT->getNumElements() == 1)
4122 return translateCopy(U, *U.getOperand(1), MIRBuilder);
4123
4124 Register Res = getOrCreateVReg(U);
4125 Register Val = getOrCreateVReg(*U.getOperand(0));
4126 Register Elt = getOrCreateVReg(*U.getOperand(1));
4127 unsigned PreferredVecIdxWidth = TLI->getVectorIdxWidth(*DL);
4128 Register Idx;
4129 if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(2))) {
4130 if (CI->getBitWidth() != PreferredVecIdxWidth) {
4131 APInt NewIdx = CI->getValue().zextOrTrunc(PreferredVecIdxWidth);
4132 auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
4133 Idx = getOrCreateVReg(*NewIdxCI);
4134 }
4135 }
4136 if (!Idx)
4137 Idx = getOrCreateVReg(*U.getOperand(2));
4138 if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
4139 const LLT VecIdxTy =
4140 MRI->getType(Idx).changeElementSize(PreferredVecIdxWidth);
4141 Idx = MIRBuilder.buildZExtOrTrunc(VecIdxTy, Idx).getReg(0);
4142 }
4143 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
4144 return true;
4145}
4146
4147bool IRTranslatorImpl::translateInsertVector(const User &U,
4148 MachineIRBuilder &MIRBuilder) {
4149 Register Dst = getOrCreateVReg(U);
4150 Register Vec = getOrCreateVReg(*U.getOperand(0));
4151 Register Elt = getOrCreateVReg(*U.getOperand(1));
4152
4153 ConstantInt *CI = cast<ConstantInt>(U.getOperand(2));
4154 unsigned PreferredVecIdxWidth = TLI->getVectorIdxWidth(*DL);
4155
4156 // Resize Index to preferred index width.
4157 if (CI->getBitWidth() != PreferredVecIdxWidth) {
4158 APInt NewIdx = CI->getValue().zextOrTrunc(PreferredVecIdxWidth);
4159 CI = ConstantInt::get(CI->getContext(), NewIdx);
4160 }
4161
4162 // If it is a <1 x Ty> vector, we have to use other means.
4163 if (auto *ResultType = dyn_cast<FixedVectorType>(U.getOperand(1)->getType());
4164 ResultType && ResultType->getNumElements() == 1) {
4165 if (auto *InputType = dyn_cast<FixedVectorType>(U.getOperand(0)->getType());
4166 InputType && InputType->getNumElements() == 1) {
4167 // We are inserting an illegal fixed vector into an illegal
4168 // fixed vector, use the scalar as it is not a legal vector type
4169 // in LLT.
4170 return translateCopy(U, Vec, MIRBuilder);
4171 }
4172 if (isa<FixedVectorType>(U.getOperand(0)->getType())) {
4173 // We are inserting an illegal fixed vector into a legal fixed
4174 // vector, use the scalar as it is not a legal vector type in
4175 // LLT.
4176 Register Idx = getOrCreateVReg(*CI);
4177 MIRBuilder.buildInsertVectorElement(Dst, Vec, Elt, Idx);
4178 return true;
4179 }
4180 if (isa<ScalableVectorType>(U.getOperand(0)->getType())) {
4181 // We are inserting an illegal fixed vector into a scalable
4182 // vector, use a scalar element insert.
4183 LLT VecIdxTy = LLT::integer(PreferredVecIdxWidth);
4184 Register Idx = getOrCreateVReg(*CI);
4185 auto ScaledIndex = MIRBuilder.buildMul(
4186 VecIdxTy, MIRBuilder.buildVScale(VecIdxTy, 1), Idx);
4187 MIRBuilder.buildInsertVectorElement(Dst, Vec, Elt, ScaledIndex);
4188 return true;
4189 }
4190 }
4191
4192 MIRBuilder.buildInsertSubvector(Dst, Vec, Elt, CI->getZExtValue());
4193 return true;
4194}
4195
4196bool IRTranslatorImpl::translateExtractElement(const User &U,
4197 MachineIRBuilder &MIRBuilder) {
4198 // If it is a <1 x Ty> vector, use the scalar as it is
4199 // not a legal vector type in LLT.
4200 if (const FixedVectorType *FVT =
4201 dyn_cast<FixedVectorType>(U.getOperand(0)->getType()))
4202 if (FVT->getNumElements() == 1)
4203 return translateCopy(U, *U.getOperand(0), MIRBuilder);
4204
4205 Register Res = getOrCreateVReg(U);
4206 Register Val = getOrCreateVReg(*U.getOperand(0));
4207 unsigned PreferredVecIdxWidth = TLI->getVectorIdxWidth(*DL);
4208 Register Idx;
4209 if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) {
4210 if (CI->getBitWidth() != PreferredVecIdxWidth) {
4211 APInt NewIdx = CI->getValue().zextOrTrunc(PreferredVecIdxWidth);
4212 auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
4213 Idx = getOrCreateVReg(*NewIdxCI);
4214 }
4215 }
4216 if (!Idx)
4217 Idx = getOrCreateVReg(*U.getOperand(1));
4218 if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
4219 const LLT VecIdxTy =
4220 MRI->getType(Idx).changeElementSize(PreferredVecIdxWidth);
4221 Idx = MIRBuilder.buildZExtOrTrunc(VecIdxTy, Idx).getReg(0);
4222 }
4223 MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
4224 return true;
4225}
4226
4227bool IRTranslatorImpl::translateExtractVector(const User &U,
4228 MachineIRBuilder &MIRBuilder) {
4229 Register Res = getOrCreateVReg(U);
4230 Register Vec = getOrCreateVReg(*U.getOperand(0));
4231 ConstantInt *CI = cast<ConstantInt>(U.getOperand(1));
4232 unsigned PreferredVecIdxWidth = TLI->getVectorIdxWidth(*DL);
4233
4234 // Resize Index to preferred index width.
4235 if (CI->getBitWidth() != PreferredVecIdxWidth) {
4236 APInt NewIdx = CI->getValue().zextOrTrunc(PreferredVecIdxWidth);
4237 CI = ConstantInt::get(CI->getContext(), NewIdx);
4238 }
4239
4240 // If it is a <1 x Ty> vector, we have to use other means.
4241 if (auto *ResultType = dyn_cast<FixedVectorType>(U.getType());
4242 ResultType && ResultType->getNumElements() == 1) {
4243 if (auto *InputType = dyn_cast<FixedVectorType>(U.getOperand(0)->getType());
4244 InputType && InputType->getNumElements() == 1) {
4245 // We are extracting an illegal fixed vector from an illegal fixed vector,
4246 // use the scalar as it is not a legal vector type in LLT.
4247 return translateCopy(U, Vec, MIRBuilder);
4248 }
4249 if (isa<FixedVectorType>(U.getOperand(0)->getType())) {
4250 // We are extracting an illegal fixed vector from a legal fixed
4251 // vector, use the scalar as it is not a legal vector type in
4252 // LLT.
4253 Register Idx = getOrCreateVReg(*CI);
4254 MIRBuilder.buildExtractVectorElement(Res, Vec, Idx);
4255 return true;
4256 }
4257 if (isa<ScalableVectorType>(U.getOperand(0)->getType())) {
4258 // We are extracting an illegal fixed vector from a scalable
4259 // vector, use a scalar element extract.
4260 LLT VecIdxTy = LLT::integer(PreferredVecIdxWidth);
4261 Register Idx = getOrCreateVReg(*CI);
4262 auto ScaledIndex = MIRBuilder.buildMul(
4263 VecIdxTy, MIRBuilder.buildVScale(VecIdxTy, 1), Idx);
4264 MIRBuilder.buildExtractVectorElement(Res, Vec, ScaledIndex);
4265 return true;
4266 }
4267 }
4268
4269 MIRBuilder.buildExtractSubvector(Res, Vec, CI->getZExtValue());
4270 return true;
4271}
4272
4273bool IRTranslatorImpl::translateShuffleVector(const User &U,
4274 MachineIRBuilder &MIRBuilder) {
4275 // A ShuffleVector that operates on scalable vectors is a splat vector where
4276 // the value of the splat vector is the 0th element of the first operand,
4277 // since the index mask operand is the zeroinitializer (undef and
4278 // poison are treated as zeroinitializer here).
4279 if (U.getOperand(0)->getType()->isScalableTy()) {
4280 Register Val = getOrCreateVReg(*U.getOperand(0));
4281 auto SplatVal = MIRBuilder.buildExtractVectorElementConstant(
4282 MRI->getType(Val).getElementType(), Val, 0);
4283 MIRBuilder.buildSplatVector(getOrCreateVReg(U), SplatVal);
4284 return true;
4285 }
4286
4287 ArrayRef<int> Mask;
4288 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&U))
4289 Mask = SVI->getShuffleMask();
4290 else
4291 Mask = cast<ConstantExpr>(U).getShuffleMask();
4292
4293 // As GISel does not represent <1 x > vectors as a separate type from scalars,
4294 // we transform shuffle_vector with a scalar output to an
4295 // ExtractVectorElement. If the input type is also scalar it becomes a Copy.
4296 unsigned DstElts = cast<FixedVectorType>(U.getType())->getNumElements();
4297 unsigned SrcElts =
4298 cast<FixedVectorType>(U.getOperand(0)->getType())->getNumElements();
4299 if (DstElts == 1) {
4300 unsigned M = Mask[0];
4301 if (SrcElts == 1) {
4302 if (M == 0 || M == 1)
4303 return translateCopy(U, *U.getOperand(M), MIRBuilder);
4304 MIRBuilder.buildUndef(getOrCreateVReg(U));
4305 } else {
4306 Register Dst = getOrCreateVReg(U);
4307 if (M < SrcElts) {
4309 Dst, getOrCreateVReg(*U.getOperand(0)), M);
4310 } else if (M < SrcElts * 2) {
4312 Dst, getOrCreateVReg(*U.getOperand(1)), M - SrcElts);
4313 } else {
4314 MIRBuilder.buildUndef(Dst);
4315 }
4316 }
4317 return true;
4318 }
4319
4320 // A single element src is transformed to a build_vector.
4321 if (SrcElts == 1) {
4324 for (int M : Mask) {
4325 LLT SrcTy = getLLTForType(*U.getOperand(0)->getType(), *DL);
4326 if (M == 0 || M == 1) {
4327 Ops.push_back(getOrCreateVReg(*U.getOperand(M)));
4328 } else {
4329 if (!Undef.isValid()) {
4330 Undef = MRI->createGenericVirtualRegister(SrcTy);
4331 MIRBuilder.buildUndef(Undef);
4332 }
4333 Ops.push_back(Undef);
4334 }
4335 }
4336 MIRBuilder.buildBuildVector(getOrCreateVReg(U), Ops);
4337 return true;
4338 }
4339
4340 ArrayRef<int> MaskAlloc = MF->allocateShuffleMask(Mask);
4341 MIRBuilder
4342 .buildInstr(TargetOpcode::G_SHUFFLE_VECTOR, {getOrCreateVReg(U)},
4343 {getOrCreateVReg(*U.getOperand(0)),
4344 getOrCreateVReg(*U.getOperand(1))})
4345 .addShuffleMask(MaskAlloc);
4346 return true;
4347}
4348
4349bool IRTranslatorImpl::translateBitInsert(const User &U,
4350 MachineIRBuilder &MIRBuilder) {
4351 Register Res = getOrCreateVReg(U);
4352 Register Base = getOrCreateVReg(*U.getOperand(0));
4353 Register Val = getOrCreateVReg(*U.getOperand(1));
4354 Register Offset = getOrCreateVReg(*U.getOperand(2));
4355 MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
4356 LLT BaseTy = MRI.getType(Base);
4357 LLT ValTy = MRI.getType(Val);
4358
4359 assert(BaseTy.getSizeInBits() >= ValTy.getSizeInBits() &&
4360 "bitinsert val wider than base should be rejected by verifier");
4361
4362 // If Val is a floating-point type, bitcast it to an integer of the same
4363 // size so buildZExtOrTrunc can safely extend or truncate it.
4364 if (ValTy.isFloat()) {
4365 ValTy = LLT::scalar(ValTy.getSizeInBits());
4366 Val = MIRBuilder.buildBitcast(ValTy, Val).getReg(0);
4367 } else if (ValTy.isPointer()) {
4368 ValTy = LLT::scalar(ValTy.getSizeInBits());
4369 Val = MIRBuilder.buildPtrToInt(ValTy, Val).getReg(0);
4370 }
4371
4372 // Convert Offset to the target's preferred shift amount type.
4373 LLT ShiftAmtTy = TLI->getPreferredShiftAmountTy(BaseTy);
4374 Register LegalOffset =
4375 MIRBuilder.buildZExtOrTrunc(ShiftAmtTy, Offset).getReg(0);
4376
4377 // Truncate or extend Val to BaseTy so only the inserted bit range remains.
4378 Register ExtVal = MIRBuilder.buildZExtOrTrunc(BaseTy, Val).getReg(0);
4379
4380 unsigned BaseBitWidth = BaseTy.getSizeInBits();
4381 unsigned ValBitWidth = ValTy.getSizeInBits();
4382 APInt InsertMask = APInt::getLowBitsSet(BaseBitWidth, ValBitWidth);
4383 Register MaskConst = MIRBuilder.buildConstant(BaseTy, InsertMask).getReg(0);
4384 Register ShiftedMask =
4385 MIRBuilder.buildShl(BaseTy, MaskConst, LegalOffset).getReg(0);
4386 Register ClearMask = MIRBuilder.buildNot(BaseTy, ShiftedMask).getReg(0);
4387 Register ClearedBase = MIRBuilder.buildAnd(BaseTy, Base, ClearMask).getReg(0);
4388 Register ShiftedVal =
4389 MIRBuilder.buildShl(BaseTy, ExtVal, LegalOffset).getReg(0);
4390 MIRBuilder.buildOr(Res, ClearedBase, ShiftedVal);
4391 return true;
4392}
4393
4394bool IRTranslatorImpl::translateBitExtract(const User &U,
4395 MachineIRBuilder &MIRBuilder) {
4396 Register Res = getOrCreateVReg(U);
4397 Register Src = getOrCreateVReg(*U.getOperand(0));
4398 Register Offset = getOrCreateVReg(*U.getOperand(1));
4399 MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
4400 LLT SrcTy = MRI.getType(Src);
4401 LLT ResTy = MRI.getType(Res);
4402
4403 assert(ResTy.getSizeInBits() <= SrcTy.getSizeInBits() &&
4404 "bitextract result wider than source should be rejected by verifier");
4405
4406 // Convert Offset to the target's preferred shift amount type.
4407 LLT ShiftAmtTy = TLI->getPreferredShiftAmountTy(SrcTy);
4408 Register LegalOffset =
4409 MIRBuilder.buildZExtOrTrunc(ShiftAmtTy, Offset).getReg(0);
4410
4411 // Shift right by Offset to bring the target field down to bit 0.
4412 Register Shifted = MIRBuilder.buildLShr(SrcTy, Src, LegalOffset).getReg(0);
4413
4414 if (ResTy.isFloat()) {
4415 // Drop into the integer domain to safely handle the size conversion
4416 LLT IntResTy = LLT::scalar(ResTy.getSizeInBits());
4417 Register IntRes = MRI.createGenericVirtualRegister(IntResTy);
4418
4419 if (SrcTy == IntResTy)
4420 MIRBuilder.buildCopy(IntRes, Shifted);
4421 else
4422 MIRBuilder.buildTrunc(IntRes, Shifted);
4423
4424 // Bitcast the raw integer bits back into the requested floating-point
4425 // register
4426 MIRBuilder.buildBitcast(Res, IntRes);
4427 } else if (ResTy.isPointer()) {
4428 // Drop into the integer domain to safely handle the size conversion
4429 LLT IntResTy = LLT::scalar(ResTy.getSizeInBits());
4430 Register IntRes = MRI.createGenericVirtualRegister(IntResTy);
4431
4432 if (SrcTy == IntResTy)
4433 MIRBuilder.buildCopy(IntRes, Shifted);
4434 else
4435 MIRBuilder.buildTrunc(IntRes, Shifted);
4436
4437 MIRBuilder.buildIntToPtr(Res, IntRes);
4438 } else {
4439 // Normal integer path
4440 if (SrcTy == ResTy)
4441 MIRBuilder.buildCopy(Res, Shifted);
4442 else
4443 MIRBuilder.buildTrunc(Res, Shifted);
4444 }
4445
4446 return true;
4447}
4448
4449bool IRTranslatorImpl::translatePHI(const User &U,
4450 MachineIRBuilder &MIRBuilder) {
4451 const PHINode &PI = cast<PHINode>(U);
4452
4453 SmallVector<MachineInstr *, 4> Insts;
4454 for (auto Reg : getOrCreateVRegs(PI)) {
4455 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {});
4456 Insts.push_back(MIB.getInstr());
4457 }
4458
4459 PendingPHIs.emplace_back(&PI, std::move(Insts));
4460 return true;
4461}
4462
4463bool IRTranslatorImpl::translateAtomicCmpXchg(const User &U,
4464 MachineIRBuilder &MIRBuilder) {
4465 const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
4466
4467 auto Flags = TLI->getAtomicMemOperandFlags(I, *DL);
4468
4469 auto Res = getOrCreateVRegs(I);
4470 Register OldValRes = Res[0];
4471 Register SuccessRes = Res[1];
4472 Register Addr = getOrCreateVReg(*I.getPointerOperand());
4473 Register Cmp = getOrCreateVReg(*I.getCompareOperand());
4474 Register NewVal = getOrCreateVReg(*I.getNewValOperand());
4475
4477 OldValRes, SuccessRes, Addr, Cmp, NewVal,
4478 *MF->getMachineMemOperand(
4479 MachinePointerInfo(I.getPointerOperand()), Flags, MRI->getType(Cmp),
4480 getMemOpAlign(I), I.getAAMetadata(), I.getSyncScopeID(),
4481 I.getSuccessOrdering(), I.getFailureOrdering()));
4482 return true;
4483}
4484
4485bool IRTranslatorImpl::translateAtomicRMW(const User &U,
4486 MachineIRBuilder &MIRBuilder) {
4487 if (!mayTranslateUserTypes(U))
4488 return false;
4489
4490 const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
4491 auto Flags = TLI->getAtomicMemOperandFlags(I, *DL);
4492
4493 Register Res = getOrCreateVReg(I);
4494 Register Addr = getOrCreateVReg(*I.getPointerOperand());
4495 Register Val = getOrCreateVReg(*I.getValOperand());
4496
4497 unsigned Opcode = 0;
4498 switch (I.getOperation()) {
4499 default:
4500 return false;
4502 Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
4503 break;
4504 case AtomicRMWInst::Add:
4505 Opcode = TargetOpcode::G_ATOMICRMW_ADD;
4506 break;
4507 case AtomicRMWInst::Sub:
4508 Opcode = TargetOpcode::G_ATOMICRMW_SUB;
4509 break;
4510 case AtomicRMWInst::And:
4511 Opcode = TargetOpcode::G_ATOMICRMW_AND;
4512 break;
4514 Opcode = TargetOpcode::G_ATOMICRMW_NAND;
4515 break;
4516 case AtomicRMWInst::Or:
4517 Opcode = TargetOpcode::G_ATOMICRMW_OR;
4518 break;
4519 case AtomicRMWInst::Xor:
4520 Opcode = TargetOpcode::G_ATOMICRMW_XOR;
4521 break;
4522 case AtomicRMWInst::Max:
4523 Opcode = TargetOpcode::G_ATOMICRMW_MAX;
4524 break;
4525 case AtomicRMWInst::Min:
4526 Opcode = TargetOpcode::G_ATOMICRMW_MIN;
4527 break;
4529 Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
4530 break;
4532 Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
4533 break;
4535 Opcode = TargetOpcode::G_ATOMICRMW_FADD;
4536 break;
4538 Opcode = TargetOpcode::G_ATOMICRMW_FSUB;
4539 break;
4541 Opcode = TargetOpcode::G_ATOMICRMW_FMAX;
4542 break;
4544 Opcode = TargetOpcode::G_ATOMICRMW_FMIN;
4545 break;
4547 Opcode = TargetOpcode::G_ATOMICRMW_FMAXIMUM;
4548 break;
4550 Opcode = TargetOpcode::G_ATOMICRMW_FMINIMUM;
4551 break;
4553 Opcode = TargetOpcode::G_ATOMICRMW_FMAXIMUMNUM;
4554 break;
4556 Opcode = TargetOpcode::G_ATOMICRMW_FMINIMUMNUM;
4557 break;
4559 Opcode = TargetOpcode::G_ATOMICRMW_UINC_WRAP;
4560 break;
4562 Opcode = TargetOpcode::G_ATOMICRMW_UDEC_WRAP;
4563 break;
4565 Opcode = TargetOpcode::G_ATOMICRMW_USUB_COND;
4566 break;
4568 Opcode = TargetOpcode::G_ATOMICRMW_USUB_SAT;
4569 break;
4570 }
4571
4572 MIRBuilder.buildAtomicRMW(
4573 Opcode, Res, Addr, Val,
4574 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4575 Flags, MRI->getType(Val), getMemOpAlign(I),
4576 I.getAAMetadata(), I.getSyncScopeID(),
4577 I.getOrdering()));
4578 return true;
4579}
4580
4581bool IRTranslatorImpl::translateFence(const User &U,
4582 MachineIRBuilder &MIRBuilder) {
4583 const FenceInst &Fence = cast<FenceInst>(U);
4584 MIRBuilder.buildFence(static_cast<unsigned>(Fence.getOrdering()),
4585 Fence.getSyncScopeID());
4586 return true;
4587}
4588
4589bool IRTranslatorImpl::translateFreeze(const User &U,
4590 MachineIRBuilder &MIRBuilder) {
4591 const ArrayRef<Register> DstRegs = getOrCreateVRegs(U);
4592 const ArrayRef<Register> SrcRegs = getOrCreateVRegs(*U.getOperand(0));
4593
4594 assert(DstRegs.size() == SrcRegs.size() &&
4595 "Freeze with different source and destination type?");
4596
4597 for (unsigned I = 0; I < DstRegs.size(); ++I) {
4598 MIRBuilder.buildFreeze(DstRegs[I], SrcRegs[I]);
4599 }
4600
4601 return true;
4602}
4603
4604void IRTranslatorImpl::finishPendingPhis() {
4605#ifndef NDEBUG
4606 DILocationVerifier Verifier;
4607 GISelObserverWrapper WrapperObserver(&Verifier);
4608 RAIIMFObsDelInstaller ObsInstall(*MF, WrapperObserver);
4609#endif // ifndef NDEBUG
4610 for (auto &Phi : PendingPHIs) {
4611 const PHINode *PI = Phi.first;
4612 if (PI->getType()->isEmptyTy())
4613 continue;
4614 ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
4615 MachineBasicBlock *PhiMBB = ComponentPHIs[0]->getParent();
4616 EntryBuilder->setDebugLoc(PI->getDebugLoc());
4617#ifndef NDEBUG
4618 Verifier.setCurrentInst(PI);
4619#endif // ifndef NDEBUG
4620
4621 SmallPtrSet<const MachineBasicBlock *, 16> SeenPreds;
4622 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
4623 auto IRPred = PI->getIncomingBlock(i);
4624 ArrayRef<Register> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
4625 for (auto *Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
4626 if (SeenPreds.count(Pred) || !PhiMBB->isPredecessor(Pred))
4627 continue;
4628 SeenPreds.insert(Pred);
4629 for (unsigned j = 0; j < ValRegs.size(); ++j) {
4630 MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
4631 MIB.addUse(ValRegs[j]);
4632 MIB.addMBB(Pred);
4633 }
4634 }
4635 }
4636 }
4637}
4638
4639void IRTranslatorImpl::translateDbgValueRecord(Value *V, bool HasArgList,
4640 const DILocalVariable *Variable,
4641 const DIExpression *Expression,
4642 const DebugLoc &DL,
4643 MachineIRBuilder &MIRBuilder) {
4644 assert(Variable->isValidLocationForIntrinsic(DL) &&
4645 "Expected inlined-at fields to agree");
4646 // Act as if we're handling a debug intrinsic.
4647 MIRBuilder.setDebugLoc(DL);
4648
4649 if (!V || HasArgList) {
4650 // DI cannot produce a valid DBG_VALUE, so produce an undef DBG_VALUE to
4651 // terminate any prior location.
4652 MIRBuilder.buildIndirectDbgValue(0, Variable, Expression);
4653 return;
4654 }
4655
4656 if (const auto *CI = dyn_cast<Constant>(V)) {
4657 MIRBuilder.buildConstDbgValue(*CI, Variable, Expression);
4658 return;
4659 }
4660
4661 if (auto *AI = dyn_cast<AllocaInst>(V);
4662 AI && AI->isStaticAlloca() && Expression->startsWithDeref()) {
4663 // If the value is an alloca and the expression starts with a
4664 // dereference, track a stack slot instead of a register, as registers
4665 // may be clobbered.
4666 auto ExprOperands = Expression->getElements();
4667 auto *ExprDerefRemoved =
4668 DIExpression::get(AI->getContext(), ExprOperands.drop_front());
4669 MIRBuilder.buildFIDbgValue(getOrCreateFrameIndex(*AI), Variable,
4670 ExprDerefRemoved);
4671 return;
4672 }
4673 if (translateIfEntryValueArgument(false, V, Variable, Expression, DL,
4674 MIRBuilder))
4675 return;
4676 for (Register Reg : getOrCreateVRegs(*V)) {
4677 // FIXME: This does not handle register-indirect values at offset 0. The
4678 // direct/indirect thing shouldn't really be handled by something as
4679 // implicit as reg+noreg vs reg+imm in the first place, but it seems
4680 // pretty baked in right now.
4681 MIRBuilder.buildDirectDbgValue(Reg, Variable, Expression);
4682 }
4683}
4684
4685void IRTranslatorImpl::translateDbgDeclareRecord(
4686 Value *Address, bool HasArgList, const DILocalVariable *Variable,
4687 const DIExpression *Expression, const DebugLoc &DL,
4688 MachineIRBuilder &MIRBuilder) {
4689 if (!Address || isa<UndefValue>(Address)) {
4690 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *Variable << "\n");
4691 return;
4692 }
4693
4694 assert(Variable->isValidLocationForIntrinsic(DL) &&
4695 "Expected inlined-at fields to agree");
4696 auto AI = dyn_cast<AllocaInst>(Address);
4697 if (AI && AI->isStaticAlloca()) {
4698 // Static allocas are tracked at the MF level, no need for DBG_VALUE
4699 // instructions (in fact, they get ignored if they *do* exist).
4700 MF->setVariableDbgInfo(Variable, Expression,
4701 getOrCreateFrameIndex(*AI), DL);
4702 return;
4703 }
4704
4705 if (translateIfEntryValueArgument(true, Address, Variable,
4706 Expression, DL,
4707 MIRBuilder))
4708 return;
4709
4710 // A dbg.declare describes the address of a source variable, so lower it
4711 // into an indirect DBG_VALUE.
4712 MIRBuilder.setDebugLoc(DL);
4713 MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address), Variable,
4714 Expression);
4715}
4716
4717void IRTranslatorImpl::translateDbgInfo(const Instruction &Inst,
4718 MachineIRBuilder &MIRBuilder) {
4719 for (DbgRecord &DR : Inst.getDbgRecordRange()) {
4720 if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
4721 MIRBuilder.setDebugLoc(DLR->getDebugLoc());
4722 assert(DLR->getLabel() && "Missing label");
4723 assert(DLR->getLabel()->isValidLocationForIntrinsic(
4724 MIRBuilder.getDebugLoc()) &&
4725 "Expected inlined-at fields to agree");
4726 MIRBuilder.buildDbgLabel(DLR->getLabel());
4727 continue;
4728 }
4729 DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
4730 const DILocalVariable *Variable = DVR.getVariable();
4731 const DIExpression *Expression = DVR.getExpression();
4732 Value *V = DVR.getVariableLocationOp(0);
4733 if (DVR.isDbgDeclare())
4734 translateDbgDeclareRecord(V, DVR.hasArgList(), Variable, Expression,
4735 DVR.getDebugLoc(), MIRBuilder);
4736 else
4737 translateDbgValueRecord(V, DVR.hasArgList(), Variable, Expression,
4738 DVR.getDebugLoc(), MIRBuilder);
4739 }
4740}
4741
4742bool IRTranslatorImpl::translate(const Instruction &Inst) {
4743 CurBuilder->setDebugLoc(Inst.getDebugLoc());
4744 CurBuilder->setPCSections(Inst.getMetadata(LLVMContext::MD_pcsections));
4745 CurBuilder->setMMRAMetadata(Inst.getMetadata(LLVMContext::MD_mmra));
4746
4747 if (TLI->fallBackToDAGISel(Inst))
4748 return false;
4749
4750 switch (Inst.getOpcode()) {
4751#define HANDLE_INST(NUM, OPCODE, CLASS) \
4752 case Instruction::OPCODE: \
4753 return translate##OPCODE(Inst, *CurBuilder.get());
4754#include "llvm/IR/Instruction.def"
4755 default:
4756 return false;
4757 }
4758}
4759
4760bool IRTranslatorImpl::translate(const Constant &C, Register Reg) {
4761 // We only emit constants into the entry block from here. To prevent jumpy
4762 // debug behaviour remove debug line.
4763 if (auto CurrInstDL = CurBuilder->getDL())
4764 EntryBuilder->setDebugLoc(DebugLoc());
4765
4766 if (auto CI = dyn_cast<ConstantInt>(&C)) {
4767 // buildConstant expects a to-be-splatted scalar ConstantInt.
4768 if (isa<VectorType>(CI->getType()))
4769 CI = ConstantInt::get(CI->getContext(), CI->getValue());
4770 EntryBuilder->buildConstant(Reg, *CI);
4771 } else if (auto CB = dyn_cast<ConstantByte>(&C)) {
4772 // Byte constants share G_CONSTANT with integers; the destination Reg's
4773 // LLT (an integer LLT, see getLLTForType) determines vector splatting.
4774 EntryBuilder->buildConstant(Reg, CB->getValue());
4775 } else if (auto CF = dyn_cast<ConstantFP>(&C)) {
4776 // buildFConstant expects a to-be-splatted scalar ConstantFP.
4777 if (isa<VectorType>(CF->getType()))
4778 CF = ConstantFP::get(CF->getContext(), CF->getValue());
4779 EntryBuilder->buildFConstant(Reg, *CF);
4780 } else if (isa<UndefValue>(C))
4781 EntryBuilder->buildUndef(Reg);
4782 else if (isa<ConstantPointerNull>(C))
4783 EntryBuilder->buildConstant(Reg, 0);
4784 else if (auto GV = dyn_cast<GlobalValue>(&C))
4785 EntryBuilder->buildGlobalValue(Reg, GV);
4786 else if (auto CPA = dyn_cast<ConstantPtrAuth>(&C)) {
4787 Register Addr = getOrCreateVReg(*CPA->getPointer());
4788 Register AddrDisc = getOrCreateVReg(*CPA->getAddrDiscriminator());
4789 EntryBuilder->buildConstantPtrAuth(Reg, CPA, Addr, AddrDisc);
4790 } else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
4791 Constant &Elt = *CAZ->getElementValue(0u);
4792 if (isa<ScalableVectorType>(CAZ->getType())) {
4793 EntryBuilder->buildSplatVector(Reg, getOrCreateVReg(Elt));
4794 return true;
4795 }
4796 // Return the scalar if it is a <1 x Ty> vector.
4797 unsigned NumElts = CAZ->getElementCount().getFixedValue();
4798 if (NumElts == 1)
4799 return translateCopy(C, Elt, *EntryBuilder);
4800 // All elements are zero so we can just use the first one.
4801 EntryBuilder->buildSplatBuildVector(Reg, getOrCreateVReg(Elt));
4802 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
4803 // Return the scalar if it is a <1 x Ty> vector.
4804 if (CV->getNumElements() == 1)
4805 return translateCopy(C, *CV->getElementAsConstant(0), *EntryBuilder);
4807 for (unsigned i = 0; i < CV->getNumElements(); ++i) {
4808 Constant &Elt = *CV->getElementAsConstant(i);
4809 Ops.push_back(getOrCreateVReg(Elt));
4810 }
4811 EntryBuilder->buildBuildVector(Reg, Ops);
4812 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
4813 switch(CE->getOpcode()) {
4814#define HANDLE_INST(NUM, OPCODE, CLASS) \
4815 case Instruction::OPCODE: \
4816 return translate##OPCODE(*CE, *EntryBuilder.get());
4817#include "llvm/IR/Instruction.def"
4818 default:
4819 return false;
4820 }
4821 } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
4822 if (CV->getNumOperands() == 1)
4823 return translateCopy(C, *CV->getOperand(0), *EntryBuilder);
4825 for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
4826 Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
4827 }
4828 EntryBuilder->buildBuildVector(Reg, Ops);
4829 } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
4830 EntryBuilder->buildBlockAddress(Reg, BA);
4831 } else
4832 return false;
4833
4834 return true;
4835}
4836
4837bool IRTranslatorImpl::mayTranslateUserTypes(const User &U) const {
4838 const TargetMachine &TM = TLI->getTargetMachine();
4839 if (LLT::getUseExtended())
4840 return true;
4841
4842 // BF16 cannot currently be represented by default LLT. To avoid miscompiles
4843 // we prevent any instructions using them by default in all targets that do
4844 // not explicitly enable it via LLT::setUseExtended(true).
4845 // SPIRV target is exception.
4846 return TM.getTargetTriple().isSPIRV() ||
4847 (!U.getType()->getScalarType()->isBFloatTy() &&
4848 !any_of(U.operands(), [](Value *V) {
4849 return V->getType()->getScalarType()->isBFloatTy();
4850 }));
4851}
4852
4853bool IRTranslatorImpl::finalizeBasicBlock(const BasicBlock &BB,
4855 for (auto &BTB : SL->BitTestCases) {
4856 // Emit header first, if it wasn't already emitted.
4857 if (!BTB.Emitted)
4858 emitBitTestHeader(BTB, BTB.Parent);
4859
4860 BranchProbability UnhandledProb = BTB.Prob;
4861 for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
4862 UnhandledProb -= BTB.Cases[j].ExtraProb;
4863 // Set the current basic block to the mbb we wish to insert the code into
4864 MachineBasicBlock *MBB = BTB.Cases[j].ThisBB;
4865 // If all cases cover a contiguous range, it is not necessary to jump to
4866 // the default block after the last bit test fails. This is because the
4867 // range check during bit test header creation has guaranteed that every
4868 // case here doesn't go outside the range. In this case, there is no need
4869 // to perform the last bit test, as it will always be true. Instead, make
4870 // the second-to-last bit-test fall through to the target of the last bit
4871 // test, and delete the last bit test.
4872
4873 MachineBasicBlock *NextMBB;
4874 if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
4875 // Second-to-last bit-test with contiguous range: fall through to the
4876 // target of the final bit test.
4877 NextMBB = BTB.Cases[j + 1].TargetBB;
4878 } else if (j + 1 == ej) {
4879 // For the last bit test, fall through to Default.
4880 NextMBB = BTB.Default;
4881 } else {
4882 // Otherwise, fall through to the next bit test.
4883 NextMBB = BTB.Cases[j + 1].ThisBB;
4884 }
4885
4886 emitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j], MBB);
4887
4888 if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
4889 // We need to record the replacement phi edge here that normally
4890 // happens in emitBitTestCase before we delete the case, otherwise the
4891 // phi edge will be lost.
4892 addMachineCFGPred({BTB.Parent->getBasicBlock(),
4893 BTB.Cases[ej - 1].TargetBB->getBasicBlock()},
4894 MBB);
4895 // Since we're not going to use the final bit test, remove it.
4896 BTB.Cases.pop_back();
4897 break;
4898 }
4899 }
4900 // This is "default" BB. We have two jumps to it. From "header" BB and from
4901 // last "case" BB, unless the latter was skipped.
4902 CFGEdge HeaderToDefaultEdge = {BTB.Parent->getBasicBlock(),
4903 BTB.Default->getBasicBlock()};
4904 addMachineCFGPred(HeaderToDefaultEdge, BTB.Parent);
4905 if (!BTB.ContiguousRange) {
4906 addMachineCFGPred(HeaderToDefaultEdge, BTB.Cases.back().ThisBB);
4907 }
4908 }
4909 SL->BitTestCases.clear();
4910
4911 for (auto &JTCase : SL->JTCases) {
4912 // Emit header first, if it wasn't already emitted.
4913 if (!JTCase.first.Emitted)
4914 emitJumpTableHeader(JTCase.second, JTCase.first, JTCase.first.HeaderBB);
4915
4916 emitJumpTable(JTCase.second, JTCase.second.MBB);
4917 }
4918 SL->JTCases.clear();
4919
4920 for (auto &SwCase : SL->SwitchCases)
4921 emitSwitchCase(SwCase, &CurBuilder->getMBB(), *CurBuilder);
4922 SL->SwitchCases.clear();
4923
4924 // Check if we need to generate stack-protector guard checks.
4925 if (SPInfo->shouldEmitSDCheck(BB)) {
4926 bool FunctionBasedInstrumentation =
4927 TLI->getSSPStackGuardCheck(*MF->getFunction().getParent(), *Libcalls);
4928 SPDescriptor.initialize(&BB, &MBB, FunctionBasedInstrumentation);
4929 }
4930 // Handle stack protector.
4931 if (SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
4932 LLVM_DEBUG(dbgs() << "Unimplemented stack protector case\n");
4933 return false;
4934 } else if (SPDescriptor.shouldEmitStackProtector()) {
4935 MachineBasicBlock *ParentMBB = SPDescriptor.getParentMBB();
4936 MachineBasicBlock *SuccessMBB = SPDescriptor.getSuccessMBB();
4937
4938 // Find the split point to split the parent mbb. At the same time copy all
4939 // physical registers used in the tail of parent mbb into virtual registers
4940 // before the split point and back into physical registers after the split
4941 // point. This prevents us needing to deal with Live-ins and many other
4942 // register allocation issues caused by us splitting the parent mbb. The
4943 // register allocator will clean up said virtual copies later on.
4945 ParentMBB, *MF->getSubtarget().getInstrInfo());
4946
4947 // Splice the terminator of ParentMBB into SuccessMBB.
4948 SuccessMBB->splice(SuccessMBB->end(), ParentMBB, SplitPoint,
4949 ParentMBB->end());
4950
4951 // Add compare/jump on neq/jump to the parent BB.
4952 if (!emitSPDescriptorParent(SPDescriptor, ParentMBB))
4953 return false;
4954
4955 // CodeGen Failure MBB if we have not codegened it yet.
4956 MachineBasicBlock *FailureMBB = SPDescriptor.getFailureMBB();
4957 if (FailureMBB->empty()) {
4958 if (!emitSPDescriptorFailure(SPDescriptor, FailureMBB))
4959 return false;
4960 }
4961
4962 // Clear the Per-BB State.
4963 SPDescriptor.resetPerBBState();
4964 }
4965 return true;
4966}
4967
4968bool IRTranslatorImpl::emitSPDescriptorParent(StackProtectorDescriptor &SPD,
4969 MachineBasicBlock *ParentBB) {
4970 CurBuilder->setInsertPt(*ParentBB, ParentBB->end());
4971 // First create the loads to the guard/stack slot for the comparison.
4972 Type *PtrIRTy = PointerType::getUnqual(MF->getFunction().getContext());
4973 const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
4974 LLT PtrMemTy = getLLTForMVT(TLI->getPointerMemTy(*DL));
4975
4976 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
4977 int FI = MFI.getStackProtectorIndex();
4978
4979 Register Guard;
4980 Register StackSlotPtr = CurBuilder->buildFrameIndex(PtrTy, FI).getReg(0);
4981 const Module &M = *ParentBB->getParent()->getFunction().getParent();
4982 Align Align = DL->getPrefTypeAlign(PointerType::getUnqual(M.getContext()));
4983
4984 // Generate code to load the content of the guard slot.
4985 Register GuardVal =
4986 CurBuilder
4987 ->buildLoad(PtrMemTy, StackSlotPtr,
4988 MachinePointerInfo::getFixedStack(*MF, FI), Align,
4990 .getReg(0);
4991
4992 // Retrieve guard check function, nullptr if instrumentation is inlined.
4993 if (const Function *GuardCheckFn = TLI->getSSPStackGuardCheck(M, *Libcalls)) {
4994 // This path is currently untestable on GlobalISel, since the only platform
4995 // that needs this seems to be Windows, and we fall back on that currently.
4996 // The code still lives here in case that changes.
4997 // Silence warning about unused variable until the code below that uses
4998 // 'GuardCheckFn' is enabled.
4999 (void)GuardCheckFn;
5000 return false;
5001#if 0
5002 // The target provides a guard check function to validate the guard value.
5003 // Generate a call to that function with the content of the guard slot as
5004 // argument.
5005 FunctionType *FnTy = GuardCheckFn->getFunctionType();
5006 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
5007 ISD::ArgFlagsTy Flags;
5008 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
5009 Flags.setInReg();
5010 CallLowering::ArgInfo GuardArgInfo(
5011 {GuardVal, FnTy->getParamType(0), {Flags}});
5012
5013 CallLowering::CallLoweringInfo Info;
5014 Info.OrigArgs.push_back(GuardArgInfo);
5015 Info.CallConv = GuardCheckFn->getCallingConv();
5016 Info.Callee = MachineOperand::CreateGA(GuardCheckFn, 0);
5017 Info.OrigRet = {Register(), FnTy->getReturnType()};
5018 if (!CLI->lowerCall(MIRBuilder, Info)) {
5019 LLVM_DEBUG(dbgs() << "Failed to lower call to stack protector check\n");
5020 return false;
5021 }
5022 return true;
5023#endif
5024 }
5025
5026 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
5027 // Otherwise, emit a volatile load to retrieve the stack guard value.
5028 if (TLI->useLoadStackGuardNode(*ParentBB->getBasicBlock()->getModule())) {
5029 Guard = MRI->createGenericVirtualRegister(PtrMemTy);
5030 getStackGuard(Guard, *CurBuilder);
5031 } else {
5032 // TODO: test using android subtarget when we support @llvm.thread.pointer.
5033 const Value *IRGuard = TLI->getSDagStackGuard(M, *Libcalls);
5034 Register GuardPtr = getOrCreateVReg(*IRGuard);
5035
5036 Guard = CurBuilder
5037 ->buildLoad(PtrMemTy, GuardPtr,
5038 MachinePointerInfo::getFixedStack(*MF, FI), Align,
5041 .getReg(0);
5042 }
5043
5044 // Perform the comparison.
5045 auto Cmp =
5046 CurBuilder->buildICmp(CmpInst::ICMP_NE, LLT::integer(1), Guard, GuardVal);
5047 // If the guard/stackslot do not equal, branch to failure MBB.
5048 CurBuilder->buildBrCond(Cmp, *SPD.getFailureMBB());
5049 // Otherwise branch to success MBB.
5050 CurBuilder->buildBr(*SPD.getSuccessMBB());
5051 return true;
5052}
5053
5054bool IRTranslatorImpl::emitSPDescriptorFailure(StackProtectorDescriptor &SPD,
5055 MachineBasicBlock *FailureBB) {
5056 const RTLIB::LibcallImpl LibcallImpl =
5057 Libcalls->getLibcallImpl(RTLIB::STACKPROTECTOR_CHECK_FAIL);
5058 if (LibcallImpl == RTLIB::Unsupported)
5059 return false;
5060
5061 CurBuilder->setInsertPt(*FailureBB, FailureBB->end());
5062
5063 CallLowering::CallLoweringInfo Info;
5064 Info.CallConv = Libcalls->getLibcallImplCallingConv(LibcallImpl);
5065
5066 StringRef LibcallName =
5068 Info.Callee = MachineOperand::CreateES(LibcallName.data());
5069 Info.OrigRet = {Register(), Type::getVoidTy(MF->getFunction().getContext()),
5070 0};
5071 if (!CLI->lowerCall(*CurBuilder, Info)) {
5072 LLVM_DEBUG(dbgs() << "Failed to lower call to stack protector fail\n");
5073 return false;
5074 }
5075
5076 // Emit a trap instruction if we are required to do so.
5077 const TargetOptions &TargetOpts = TLI->getTargetMachine().Options;
5078 if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
5079 CurBuilder->buildInstr(TargetOpcode::G_TRAP);
5080
5081 return true;
5082}
5083
5084void IRTranslatorImpl::finalizeFunction() {
5085 // Release the memory used by the different maps we
5086 // needed during the translation.
5087 PendingPHIs.clear();
5088 VMap.reset();
5089 FrameIndices.clear();
5090 MachinePreds.clear();
5091 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
5092 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
5093 // destroying it twice (in ~IRTranslator() and ~LLVMContext())
5094 EntryBuilder.reset();
5095 CurBuilder.reset();
5096 FuncInfo.clear();
5097 SPDescriptor.resetPerFunctionState();
5098}
5099
5100/// Returns true if a BasicBlock \p BB within a variadic function contains a
5101/// variadic musttail call.
5102static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB) {
5103 if (!IsVarArg)
5104 return false;
5105
5106 // Walk the block backwards, because tail calls usually only appear at the end
5107 // of a block.
5108 return llvm::any_of(llvm::reverse(BB), [](const Instruction &I) {
5109 const auto *CI = dyn_cast<CallInst>(&I);
5110 return CI && CI->isMustTailCall();
5111 });
5112}
5113
5115 MachineFunction &CurMF, function_ref<GISelCSEInfo *()> GetCSEInfo,
5116 bool ShouldSkipOpts, function_ref<AAResults *()> GetAAResults,
5118 function_ref<AssumptionCache *()> GetAC, TargetLibraryInfo *LibraryInfo,
5119 const LibcallLoweringInfo *LibcallInfo, SSPLayoutInfo *StackProtectorInfo) {
5120 MF = &CurMF;
5121 const Function &F = MF->getFunction();
5122 ORE = std::make_unique<OptimizationRemarkEmitter>(&F);
5123 CLI = MF->getSubtarget().getCallLowering();
5124 SPInfo = StackProtectorInfo;
5125
5126 if (CLI->fallBackToDAGISel(*MF)) {
5127 OptimizationRemarkMissed R("gisel-ir-translator", "GISelFailure",
5128 F.getSubprogram(), &F.getEntryBlock());
5129 R << "unable to lower function: "
5130 << ore::NV("Prototype", F.getFunctionType());
5131
5132 reportTranslationError(*MF, *ORE, R);
5133 return false;
5134 }
5135
5136 // Set the CSEConfig and run the analysis.
5137 GISelCSEInfo *CSEInfo = nullptr;
5138
5139 bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences()
5141 : true;
5142
5143 const TargetSubtargetInfo &Subtarget = MF->getSubtarget();
5144 TLI = Subtarget.getTargetLowering();
5145
5146 if (EnableCSE) {
5147 EntryBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
5148 CSEInfo = GetCSEInfo();
5149 EntryBuilder->setCSEInfo(CSEInfo);
5150 CurBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
5151 CurBuilder->setCSEInfo(CSEInfo);
5152 } else {
5153 EntryBuilder = std::make_unique<MachineIRBuilder>();
5154 CurBuilder = std::make_unique<MachineIRBuilder>();
5155 }
5156 CLI = Subtarget.getCallLowering();
5157 CurBuilder->setMF(*MF);
5158 EntryBuilder->setMF(*MF);
5159 MRI = &MF->getRegInfo();
5160 DL = &F.getDataLayout();
5161 const TargetMachine &TM = MF->getTarget();
5162 EnableOpts = OptLevel != CodeGenOptLevel::None && !ShouldSkipOpts;
5163 FuncInfo.MF = MF;
5164 // Prefer the "exception-model" module flag, else the TargetOptions default.
5165 FuncInfo.ExceptionModel = F.getParent()->getExceptionModel();
5166 if (FuncInfo.ExceptionModel == ExceptionHandling::Default)
5167 FuncInfo.ExceptionModel = TM.getExceptionModel();
5168 if (EnableOpts) {
5169 AA = GetAAResults();
5170 FuncInfo.BPI = GetBPI();
5171 AC = GetAC();
5172 } else {
5173 AA = nullptr;
5174 FuncInfo.BPI = nullptr;
5175 AC = nullptr;
5176 }
5177 LibInfo = LibraryInfo;
5178 Libcalls = LibcallInfo;
5179
5180 FuncInfo.CanLowerReturn = CLI->checkReturnTypeForCallConv(*MF);
5181
5182 SL = std::make_unique<GISelSwitchLowering>(this, FuncInfo);
5183 SL->init(*TLI, TM, *DL);
5184
5185 assert(PendingPHIs.empty() && "stale PHIs");
5186
5187 // Targets which want to use big endian can enable it using
5188 // enableBigEndian()
5189 if (!DL->isLittleEndian() && !CLI->enableBigEndian()) {
5190 // Currently we don't properly handle big endian code.
5191 OptimizationRemarkMissed R("gisel-ir-translator", "GISelFailure",
5192 F.getSubprogram(), &F.getEntryBlock());
5193 R << "unable to translate in big endian mode";
5194 reportTranslationError(*MF, *ORE, R);
5195 return false;
5196 }
5197
5198 // Release the per-function state when we return, whether we succeeded or not.
5199 llvm::scope_exit FinalizeOnReturn([this]() { finalizeFunction(); });
5200
5201 // Setup a separate basic-block for the arguments and constants
5202 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
5203 MF->push_back(EntryBB);
5204 EntryBuilder->setMBB(*EntryBB);
5205
5206 DebugLoc DbgLoc = F.getEntryBlock().getFirstNonPHIIt()->getDebugLoc();
5207 SwiftError.setFunction(CurMF);
5208 SwiftError.createEntriesInEntryBlock(DbgLoc);
5209
5210 bool IsVarArg = F.isVarArg();
5211 bool HasMustTailInVarArgFn = false;
5212 // Use arguments and instructions to estimate the number of mapped values and
5213 // virtual registers.
5214 unsigned NumValues = F.arg_size();
5215
5216 // Create all blocks, in IR order, to preserve the layout.
5217 FuncInfo.MBBMap.resize(F.getMaxBlockNumber());
5218 for (const BasicBlock &BB: F) {
5219 NumValues += BB.size();
5220 auto *&MBB = FuncInfo.MBBMap[BB.getNumber()];
5221
5222 MBB = MF->CreateMachineBasicBlock(&BB);
5223 MF->push_back(MBB);
5224
5225 // Only mark the block if the BlockAddress actually has users. The
5226 // hasAddressTaken flag may be stale if the BlockAddress was optimized away
5227 // but the constant still exists in the uniquing table.
5228 if (BB.hasAddressTaken()) {
5229 if (BlockAddress *BA = BlockAddress::lookup(&BB))
5230 if (!BA->hasZeroLiveUses())
5231 MBB->setAddressTakenIRBlock(const_cast<BasicBlock *>(&BB));
5232 }
5233
5234 if (!HasMustTailInVarArgFn)
5235 HasMustTailInVarArgFn = checkForMustTailInVarArgFn(IsVarArg, BB);
5236 }
5237
5238 VMap.reserveVRegs(NumValues);
5239 MRI->reserveVirtRegs(NumValues);
5240
5241 MF->getFrameInfo().setHasMustTailInVarArgFunc(HasMustTailInVarArgFn);
5242
5243 // Make our arguments/constants entry block fallthrough to the IR entry block.
5244 EntryBB->addSuccessor(&getMBB(F.front()));
5245
5246 // Lower the actual args into this basic block.
5247 SmallVector<ArrayRef<Register>, 8> VRegArgs;
5248 for (const Argument &Arg: F.args()) {
5249 if (DL->getTypeStoreSize(Arg.getType()).isZero())
5250 continue; // Don't handle zero sized types.
5251 ArrayRef<Register> VRegs = getOrCreateVRegs(Arg);
5252 VRegArgs.push_back(VRegs);
5253
5254 if (CLI->supportSwiftError() && Arg.hasSwiftErrorAttr()) {
5255 assert(VRegs.size() == 1 && "Too many vregs for Swift error");
5256 SwiftError.setCurrentVReg(EntryBB, SwiftError.getFunctionArg(), VRegs[0]);
5257 }
5258 }
5259
5260 if (!CLI->lowerFormalArguments(*EntryBuilder, F, VRegArgs, FuncInfo)) {
5261 OptimizationRemarkMissed R("gisel-ir-translator", "GISelFailure",
5262 F.getSubprogram(), &F.getEntryBlock());
5263 R << "unable to lower arguments: "
5264 << ore::NV("Prototype", F.getFunctionType());
5265 reportTranslationError(*MF, *ORE, R);
5266 return false;
5267 }
5268
5269 // Need to visit defs before uses when translating instructions.
5270 GISelObserverWrapper WrapperObserver;
5271 if (EnableCSE && CSEInfo)
5272 WrapperObserver.addObserver(CSEInfo);
5273 {
5275#ifndef NDEBUG
5276 DILocationVerifier Verifier;
5277 WrapperObserver.addObserver(&Verifier);
5278#endif // ifndef NDEBUG
5279 RAIIMFObsDelInstaller ObsInstall(*MF, WrapperObserver);
5280 for (const BasicBlock *BB : RPOT) {
5281 MachineBasicBlock &MBB = getMBB(*BB);
5282 // Set the insertion point of all the following translations to
5283 // the end of this basic block.
5284 CurBuilder->setMBB(MBB);
5285 HasTailCall = false;
5286 for (const Instruction &Inst : *BB) {
5287 // If we translated a tail call in the last step, then we know
5288 // everything after the call is either a return, or something that is
5289 // handled by the call itself. (E.g. a lifetime marker or assume
5290 // intrinsic.) In this case, we should stop translating the block and
5291 // move on.
5292 if (HasTailCall)
5293 break;
5294#ifndef NDEBUG
5295 Verifier.setCurrentInst(&Inst);
5296#endif // ifndef NDEBUG
5297
5298 // Translate any debug-info attached to the instruction.
5299 translateDbgInfo(Inst, *CurBuilder);
5300
5301 if (translate(Inst))
5302 continue;
5303
5304 OptimizationRemarkMissed R("gisel-ir-translator", "GISelFailure",
5305 Inst.getDebugLoc(), BB);
5306 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
5307
5308 if (ORE->allowExtraAnalysis("gisel-ir-translator")) {
5309 std::string InstStrStorage;
5310 raw_string_ostream InstStr(InstStrStorage);
5311 InstStr << Inst;
5312
5313 R << ": '" << InstStrStorage << "'";
5314 }
5315
5316 reportTranslationError(*MF, *ORE, R);
5317 return false;
5318 }
5319
5320 if (!finalizeBasicBlock(*BB, MBB)) {
5321 OptimizationRemarkMissed R("gisel-ir-translator", "GISelFailure",
5322 BB->getTerminator()->getDebugLoc(), BB);
5323 R << "unable to translate basic block";
5324 reportTranslationError(*MF, *ORE, R);
5325 return false;
5326 }
5327 }
5328#ifndef NDEBUG
5329 WrapperObserver.removeObserver(&Verifier);
5330#endif
5331 }
5332
5333 finishPendingPhis();
5334
5335 SwiftError.propagateVRegs();
5336
5337 // Merge the argument lowering and constants block with its single
5338 // successor, the LLVM-IR entry block. We want the basic block to
5339 // be maximal.
5340 assert(EntryBB->succ_size() == 1 &&
5341 "Custom BB used for lowering should have only one successor");
5342 // Get the successor of the current entry block.
5343 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
5344 assert(NewEntryBB.pred_size() == 1 &&
5345 "LLVM-IR entry block has a predecessor!?");
5346 // Move all the instruction from the current entry block to the
5347 // new entry block.
5348 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
5349 EntryBB->end());
5350
5351 // Update the live-in information for the new entry block.
5352 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
5353 NewEntryBB.addLiveIn(LiveIn);
5354 NewEntryBB.sortUniqueLiveIns();
5355
5356 // Get rid of the now empty basic block.
5357 EntryBB->removeSuccessor(&NewEntryBB);
5358 MF->remove(EntryBB);
5359 MF->deleteMachineBasicBlock(EntryBB);
5360
5361 assert(&MF->front() == &NewEntryBB &&
5362 "New entry wasn't next in the list of basic block!");
5363
5364 // Initialize stack protector information.
5365 SPInfo->copyToMachineFrameInfo(MF->getFrameInfo());
5366
5367 return false;
5368}
5369
5371 const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
5372 Function &F = MF.getFunction();
5373
5374 bool ShouldSkipOpts = skipFunction(MF.getFunction());
5375 return Impl->runOnMachineFunction(
5376 MF,
5377 [&]() {
5381 return &Wrapper.get(TPC.getCSEConfig());
5382 },
5383 ShouldSkipOpts,
5384 [&]() { return &getAnalysis<AAResultsWrapperPass>().getAAResults(); },
5385 [&]() {
5387 },
5388 [&]() {
5389 return &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
5390 MF.getFunction());
5391 },
5393 &getAnalysis<LibcallLoweringInfoWrapper>().getLibcallLowering(
5394 *F.getParent(), Subtarget),
5395 &getAnalysis<StackProtector>().getLayoutInfo());
5396}
5397
5399 : Impl(std::make_unique<IRTranslatorImpl>(OptLevel)) {}
5400
5403
5406 const TargetSubtargetInfo &Subtarget = MF.getSubtarget();
5407 Function &F = MF.getFunction();
5408
5409 bool ShouldSkipOpts = MF.getFunction().hasOptNone() ||
5412 .getManager();
5413 auto &MAMProxy =
5415 const ModuleLibcallLoweringInfo *MLLI =
5416 MAMProxy.getCachedResult<LibcallLoweringModuleAnalysis>(*F.getParent());
5417 if (!MLLI)
5419 "LibcallLoweringModuleAnalysis must be available for IRTranslator");
5420 Impl->runOnMachineFunction(
5421 MF, [&]() { return MFAM.getResult<GISelCSEAnalysis>(MF).get(); },
5422 ShouldSkipOpts, [&]() { return &FAM.getResult<AAManager>(F); },
5423 [&]() { return &FAM.getResult<BranchProbabilityAnalysis>(F); },
5424 [&]() { return &FAM.getResult<AssumptionAnalysis>(F); },
5425 &FAM.getResult<TargetLibraryAnalysis>(F),
5426 &getLibcallLowering(*MLLI, Subtarget),
5427 &FAM.getResult<SSPLayoutAnalysis>(F));
5428
5430}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
amdgpu aa AMDGPU Address space based Alias Analysis Wrapper
unsigned uint64_t
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Provides analysis for continuously CSEing during GISel passes.
This file implements a version of MachineIRBuilder which CSEs insts within a MachineBasicBlock.
This file describes how to lower LLVM calls to machine code calls.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil translate DXIL Translate Metadata
This contains common code to allow clients to notify changes to machine instr.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
static cl::opt< bool > EnableCSEInIRTranslator("enable-cse-in-ir-translator", cl::desc("Should enable CSE in ir-translator"), cl::init(false))
static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB)
Returns true if a BasicBlock BB within a variadic function contains a variadic musttail call.
static unsigned getConvOpcode(Intrinsic::ID ID)
static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL)
static unsigned getConstrainedOpcode(Intrinsic::ID ID)
IRTranslator LLVM IR MI
IRTranslator LLVM IR static false void reportTranslationError(MachineFunction &MF, OptimizationRemarkEmitter &ORE, OptimizationRemarkMissed &R)
static bool isValInBlock(const Value *V, const BasicBlock *BB)
static bool isSwiftError(const Value *V)
This file declares the IRTranslator pass.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This file describes how to lower LLVM inline asm to machine code INLINEASM.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
Implement a low-level type suitable for MachineInstr level instruction selection.
Implement a low-level type suitable for MachineInstr level instruction selection.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file declares the MachineIRBuilder class.
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
This file contains the declarations for metadata subclasses.
Type::TypeID TypeID
uint64_t High
OptimizedStructLayoutField Field
FunctionAnalysisManager FAM
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
const SmallVectorImpl< MachineOperand > & Cond
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
verify safepoint Safepoint IR Verifier
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:484
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
Value * RHS
Value * LHS
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
an instruction to allocate memory on the stack
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
LLVM_ABI TypeSize getAllocationBaseSize(const DataLayout &DL) const
Get the size of the allocated type.
PointerType * getType() const
Overload to return most specific pointer type.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
const Value * getArraySize() const
Get the number of elements allocated.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM_ABI bool hasSwiftErrorAttr() const
Return true if this argument has the swifterror attribute.
Definition Function.cpp:150
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
@ Add
*p = old + v
@ FAdd
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ FSub
*p = old - v
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
@ Nand
*p = ~(old & v)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
unsigned getNumber() const
Definition BasicBlock.h:95
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:672
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
size_t size() const
Definition BasicBlock.h:467
LLVM_ABI const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
The address of a basic block.
Definition Constants.h:1088
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
Legacy analysis pass which computes BlockFrequencyInfo.
Analysis pass which computes BranchProbabilityInfo.
Legacy analysis pass which computes BranchProbabilityInfo.
Analysis providing branch probability information.
LLVM_ABI BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
static constexpr BranchProbability getOne()
static constexpr BranchProbability getUnknown()
static constexpr BranchProbability getZero()
static void normalizeProbabilities(ProbabilityIter Begin, ProbabilityIter End)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isInlineAsm() const
Check if this call is an inline asm statement.
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
MaybeAlign getParamAlign(unsigned ArgNo) const
Extract the alignment for a call or parameter (0=unknown).
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
bool isConvergent() const
Determine if the invoke is convergent.
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ 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
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
bool isFPPredicate() const
Definition InstrTypes.h:845
bool isIntPredicate() const
Definition InstrTypes.h:846
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
This is the common base class for constrained floating point intrinsics.
LLVM_ABI std::optional< fp::ExceptionBehavior > getExceptionBehavior() const
LLVM_ABI unsigned getNonMetadataArgCount() const
DWARF expression.
LLVM_ABI bool isEntryValue() const
Check if the expression consists of exactly one entry value operand.
static LLVM_ABI DIExpression * append(const DIExpression *Expr, ArrayRef< uint64_t > Ops)
Append the opcodes Ops to DIExpr.
LLVM_ABI bool startsWithDeref() const
Return whether the first element a DW_OP_deref.
ArrayRef< uint64_t > getElements() const
bool isValidLocationForIntrinsic(const DILocation *DL) const
Check that a location is valid for this label.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Value * getAddress() const
DILabel * getLabel() const
DebugLoc getDebugLoc() const
Value * getValue(unsigned OpIdx=0) const
DILocalVariable * getVariable() const
DIExpression * getExpression() const
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
A debug info location.
Definition DebugLoc.h:126
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:680
Class representing an expression and its matching format.
This instruction extracts a struct member or array element value from an aggregate value.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:843
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition Pass.cpp:196
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
Constant * getPersonalityFn() const
Get the personality function associated with this function.
const Function & getFunction() const
Definition Function.h:167
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
Definition Function.h:252
bool hasOptNone() const
Do not optimize this function (-O0).
Definition Function.h:686
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:356
The actual analysis pass wrapper.
Definition CSEInfo.h:244
Simple wrapper that does the following.
Definition CSEInfo.h:214
The CSE Analysis object.
Definition CSEInfo.h:72
Abstract class that contains various methods for clients to notify about changes.
Simple wrapper observer that takes several observers, and calls each one for each event.
void removeObserver(GISelChangeObserver *O)
void addObserver(GISelChangeObserver *O)
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
bool hasExternalWeakLinkage() const
bool hasDLLImportStorageClass() const
Module * getParent()
Get the module that this global value is contained inside of...
bool isTailCall(const MachineInstr &MI) const override
IRTranslatorImpl(CodeGenOptLevel OptLevel=CodeGenOptLevel::None)
bool runOnMachineFunction(MachineFunction &MF, function_ref< GISelCSEInfo *()> GetCSEInfo, bool ShouldSkipOpts, function_ref< AAResults *()> GetAAResults, function_ref< BranchProbabilityInfo *()> GetBPI, function_ref< AssumptionCache *()> GetAC, TargetLibraryInfo *LibraryInfo, const LibcallLoweringInfo *LibcallInfo, SSPLayoutInfo *StackProtectorInfo)
IRTranslatorLegacy(CodeGenOptLevel OptLevel=CodeGenOptLevel::None)
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
~IRTranslatorLegacy() override
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI ~IRTranslatorPass()
LLVM_ABI IRTranslatorPass(CodeGenOptLevel OptLevel)
bool lowerInlineAsm(MachineIRBuilder &MIRBuilder, const CallBase &CB, std::function< ArrayRef< Register >(const Value &Val)> GetOrCreateVRegs) const
Lower the given inline asm call instruction GetOrCreateVRegs is a callback to materialize a register ...
This instruction inserts a struct field of array element value into an aggregate value.
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange() const
Return a range over the DbgRecords attached to this instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI bool hasAllowReassoc() const LLVM_READONLY
Determine whether the allow-reassociation flag is set.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
static bool getUseExtended()
constexpr bool isScalar() const
constexpr LLT changeElementType(LLT NewEltTy) const
If this type is a vector, return a vector with the same number of elements but the new element type.
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
constexpr uint16_t getNumElements() const
Returns the number of elements in a vector LLT.
constexpr bool isFloat() const
constexpr bool isVector() const
static constexpr LLT pointer(unsigned AddressSpace, unsigned SizeInBits)
Get a low-level pointer in the given address space.
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
constexpr bool isPointer() const
static constexpr LLT fixed_vector(unsigned NumElements, unsigned ScalarSizeInBits)
Get a low-level fixed-width vector of some number of elements and element width.
constexpr bool isFixedVector() const
Returns true if the LLT is a fixed vector.
static constexpr LLT token()
Get a low-level token; just a scalar with zero bits (or no size).
static LLT integer(unsigned SizeInBits)
LLT changeElementSize(unsigned NewEltSize) const
If this type is a vector, return a vector with the same number of elements but the new element size.
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
Tracks which library functions to use for a particular subtarget or function.
Value * getPointerOperand()
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
static LocationSize precise(uint64_t Value)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
void normalizeSuccProbs()
Normalize probabilities of all successors so that the sum of them becomes one.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
void push_back(MachineInstr *MI)
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void setSuccProbability(succ_iterator I, BranchProbability Prob)
Set successor probability of a given iterator.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
SmallVectorImpl< MachineBasicBlock * >::iterator succ_iterator
LLVM_ABI void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
LLVM_ABI bool isPredecessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a predecessor of this block.
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
void setIsEHPad(bool V=true)
Indicates the block is a landing pad.
int getStackProtectorIndex() const
Return the index for the stack protector object.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
Helper class to build MachineInstr.
MachineInstrBuilder buildFPTOUI_SAT(const DstOp &Dst, const SrcOp &Src0)
Build and insert Res = G_FPTOUI_SAT Src0.
MachineInstrBuilder buildFMul(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
MachineInstrBuilder buildFreeze(const DstOp &Dst, const SrcOp &Src)
Build and insert Dst = G_FREEZE Src.
MachineInstrBuilder buildBr(MachineBasicBlock &Dest)
Build and insert G_BR Dest.
MachineInstrBuilder buildModf(const DstOp &Fract, const DstOp &Int, const SrcOp &Src, std::optional< unsigned > Flags=std::nullopt)
Build and insert Fract, Int = G_FMODF Src.
LLVMContext & getContext() const
MachineInstrBuilder buildAdd(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_ADD Op0, Op1.
MachineInstrBuilder buildUndef(const DstOp &Res)
Build and insert Res = IMPLICIT_DEF.
MachineInstrBuilder buildResetFPMode()
Build and insert G_RESET_FPMODE.
MachineInstrBuilder buildNot(const DstOp &Dst, const SrcOp &Src0)
Build and insert a bitwise not, NegOne = G_CONSTANT -1 Res = G_OR Op0, NegOne.
MachineInstrBuilder buildFPTOSI_SAT(const DstOp &Dst, const SrcOp &Src0)
Build and insert Res = G_FPTOSI_SAT Src0.
MachineInstrBuilder buildUCmp(const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1)
Build and insert a Res = G_UCMP Op0, Op1.
MachineInstrBuilder buildJumpTable(const LLT PtrTy, unsigned JTI)
Build and insert Res = G_JUMP_TABLE JTI.
MachineInstrBuilder buildGetRounding(const DstOp &Dst)
Build and insert Dst = G_GET_ROUNDING.
MachineInstrBuilder buildSCmp(const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1)
Build and insert a Res = G_SCMP Op0, Op1.
MachineInstrBuilder buildFence(unsigned Ordering, unsigned Scope)
Build and insert G_FENCE Ordering, Scope.
MachineInstrBuilder buildSelect(const DstOp &Res, const SrcOp &Tst, const SrcOp &Op0, const SrcOp &Op1, std::optional< unsigned > Flags=std::nullopt)
Build and insert a Res = G_SELECT Tst, Op0, Op1.
MachineInstrBuilder buildFMA(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, const SrcOp &Src2, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_FMA Op0, Op1, Op2.
MachineInstrBuilder buildMul(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_MUL Op0, Op1.
MachineInstrBuilder buildInsertSubvector(const DstOp &Res, const SrcOp &Src0, const SrcOp &Src1, unsigned Index)
Build and insert Res = G_INSERT_SUBVECTOR Src0, Src1, Idx.
MachineInstrBuilder buildAnd(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1)
Build and insert Res = G_AND Op0, Op1.
MachineInstrBuilder buildCast(const DstOp &Dst, const SrcOp &Src)
Build and insert an appropriate cast between two registers of equal size.
MachineInstrBuilder buildICmp(CmpInst::Predicate Pred, const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1, std::optional< unsigned > Flags=std::nullopt)
Build and insert a Res = G_ICMP Pred, Op0, Op1.
MachineInstrBuilder buildLShr(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
MachineBasicBlock::iterator getInsertPt()
Current insertion point for new instructions.
MachineInstrBuilder buildSExtOrTrunc(const DstOp &Res, const SrcOp &Op)
Build and insert Res = G_SEXT Op, Res = G_TRUNC Op, or Res = COPY Op depending on the differing sizes...
MachineInstrBuilder buildAtomicRMW(unsigned Opcode, const DstOp &OldValRes, const SrcOp &Addr, const SrcOp &Val, MachineMemOperand &MMO)
Build and insert OldValRes<def> = G_ATOMICRMW_<Opcode> Addr, Val, MMO.
MachineInstrBuilder buildSub(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_SUB Op0, Op1.
MachineInstrBuilder buildIntrinsic(Intrinsic::ID ID, ArrayRef< Register > Res, bool HasSideEffects, bool isConvergent)
Build and insert a G_INTRINSIC instruction.
MachineInstrBuilder buildVScale(const DstOp &Res, unsigned MinElts)
Build and insert Res = G_VSCALE MinElts.
MachineInstrBuilder buildSplatBuildVector(const DstOp &Res, const SrcOp &Src)
Build and insert Res = G_BUILD_VECTOR with Src replicated to fill the number of elements.
MachineInstrBuilder buildSetFPMode(const SrcOp &Src)
Build and insert G_SET_FPMODE Src.
MachineInstrBuilder buildIntToPtr(const DstOp &Dst, const SrcOp &Src)
Build and insert a G_INTTOPTR instruction.
MachineInstrBuilder buildIndirectDbgValue(Register Reg, const MDNode *Variable, const MDNode *Expr)
Build and insert a DBG_VALUE instruction expressing the fact that the associated Variable lives in me...
MachineInstrBuilder buildBuildVector(const DstOp &Res, ArrayRef< Register > Ops)
Build and insert Res = G_BUILD_VECTOR Op0, ...
MachineInstrBuilder buildConstDbgValue(const Constant &C, const MDNode *Variable, const MDNode *Expr)
Build and insert a DBG_VALUE instructions specifying that Variable is given by C (suitably modified b...
MachineInstrBuilder buildBrCond(const SrcOp &Tst, MachineBasicBlock &Dest)
Build and insert G_BRCOND Tst, Dest.
std::optional< MachineInstrBuilder > materializeObjectPtrOffset(Register &Res, Register Op0, const LLT ValueTy, uint64_t Value)
Materialize and insert an instruction with appropriate flags for addressing some offset of an object,...
MachineInstrBuilder buildSetRounding(const SrcOp &Src)
Build and insert G_SET_ROUNDING.
MachineInstrBuilder buildExtractVectorElement(const DstOp &Res, const SrcOp &Val, const SrcOp &Idx)
Build and insert Res = G_EXTRACT_VECTOR_ELT Val, Idx.
MachineInstrBuilder buildLoad(const DstOp &Res, const SrcOp &Addr, MachineMemOperand &MMO)
Build and insert Res = G_LOAD Addr, MMO.
MachineInstrBuilder buildPtrAdd(const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_PTR_ADD Op0, Op1.
MachineInstrBuilder buildZExtOrTrunc(const DstOp &Res, const SrcOp &Op)
Build and insert Res = G_ZEXT Op, Res = G_TRUNC Op, or Res = COPY Op depending on the differing sizes...
MachineInstrBuilder buildExtractVectorElementConstant(const DstOp &Res, const SrcOp &Val, const int Idx)
Build and insert Res = G_EXTRACT_VECTOR_ELT Val, Idx.
MachineInstrBuilder buildShl(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
MachineInstrBuilder buildStore(const SrcOp &Val, const SrcOp &Addr, MachineMemOperand &MMO)
Build and insert G_STORE Val, Addr, MMO.
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
MachineInstrBuilder buildFrameIndex(const DstOp &Res, int Idx)
Build and insert Res = G_FRAME_INDEX Idx.
MachineInstrBuilder buildDirectDbgValue(Register Reg, const MDNode *Variable, const MDNode *Expr)
Build and insert a DBG_VALUE instruction expressing the fact that the associated Variable lives in Re...
MachineInstrBuilder buildDbgLabel(const MDNode *Label)
Build and insert a DBG_LABEL instructions specifying that Label is given.
MachineInstrBuilder buildBrJT(Register TablePtr, unsigned JTI, Register IndexReg)
Build and insert G_BRJT TablePtr, JTI, IndexReg.
MachineInstrBuilder buildDynStackAlloc(const DstOp &Res, const SrcOp &Size, Align Alignment)
Build and insert Res = G_DYN_STACKALLOC Size, Align.
MachineInstrBuilder buildFIDbgValue(int FI, const MDNode *Variable, const MDNode *Expr)
Build and insert a DBG_VALUE instruction expressing the fact that the associated Variable lives in th...
MachineInstrBuilder buildResetFPEnv()
Build and insert G_RESET_FPENV.
MachineInstrBuilder buildTrunc(const DstOp &Res, const SrcOp &Op, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_TRUNC Op.
void setDebugLoc(const DebugLoc &DL)
Set the debug location to DL for all the next build instructions.
const MachineBasicBlock & getMBB() const
Getter for the basic block we currently build.
MachineInstrBuilder buildInsertVectorElement(const DstOp &Res, const SrcOp &Val, const SrcOp &Elt, const SrcOp &Idx)
Build and insert Res = G_INSERT_VECTOR_ELT Val, Elt, Idx.
MachineInstrBuilder buildAtomicCmpXchgWithSuccess(const DstOp &OldValRes, const DstOp &SuccessRes, const SrcOp &Addr, const SrcOp &CmpVal, const SrcOp &NewVal, MachineMemOperand &MMO)
Build and insert OldValRes<def>, SuccessRes<def> = / G_ATOMIC_CMPXCHG_WITH_SUCCESS Addr,...
void setMBB(MachineBasicBlock &MBB)
Set the insertion point to the end of MBB.
MachineInstrBuilder buildBitcast(const DstOp &Dst, const SrcOp &Src)
Build and insert Dst = G_BITCAST Src.
const DebugLoc & getDebugLoc()
Get the current instruction's debug location.
MachineInstrBuilder buildTrap(bool Debug=false)
Build and insert G_TRAP or G_DEBUGTRAP.
MachineInstrBuilder buildFFrexp(const DstOp &Fract, const DstOp &Exp, const SrcOp &Src, std::optional< unsigned > Flags=std::nullopt)
Build and insert Fract, Exp = G_FFREXP Src.
MachineRegisterInfo * getMRI()
Getter for MRI.
MachineInstrBuilder buildOr(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_OR Op0, Op1.
MachineInstrBuilder buildFSincos(const DstOp &Sin, const DstOp &Cos, const SrcOp &Src, std::optional< unsigned > Flags=std::nullopt)
Build and insert Sin, Cos = G_FSINCOS Src.
MachineInstrBuilder buildShuffleVector(const DstOp &Res, const SrcOp &Src1, const SrcOp &Src2, ArrayRef< int > Mask)
Build and insert Res = G_SHUFFLE_VECTOR Src1, Src2, Mask.
MachineInstrBuilder buildInstrNoInsert(unsigned Opcode)
Build but don't insert <empty> = Opcode <empty>.
MachineInstrBuilder buildCopy(const DstOp &Res, const SrcOp &Op)
Build and insert Res = COPY Op.
MachineInstrBuilder buildPrefetch(const SrcOp &Addr, unsigned RW, unsigned Locality, unsigned CacheType, MachineMemOperand &MMO)
Build and insert G_PREFETCH Addr, RW, Locality, CacheType.
MachineInstrBuilder buildExtractSubvector(const DstOp &Res, const SrcOp &Src, unsigned Index)
Build and insert Res = G_EXTRACT_SUBVECTOR Src, Idx0.
const DataLayout & getDataLayout() const
MachineInstrBuilder buildBrIndirect(Register Tgt)
Build and insert G_BRINDIRECT Tgt.
MachineInstrBuilder buildSplatVector(const DstOp &Res, const SrcOp &Val)
Build and insert Res = G_SPLAT_VECTOR Val.
MachineInstrBuilder buildStepVector(const DstOp &Res, unsigned Step)
Build and insert Res = G_STEP_VECTOR Step.
virtual MachineInstrBuilder buildConstant(const DstOp &Res, const ConstantInt &Val)
Build and insert Res = G_CONSTANT Val.
MachineInstrBuilder buildFCmp(CmpInst::Predicate Pred, const DstOp &Res, const SrcOp &Op0, const SrcOp &Op1, std::optional< unsigned > Flags=std::nullopt)
Build and insert a Res = G_FCMP PredOp0, Op1.
MachineInstrBuilder buildFAdd(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_FADD Op0, Op1.
MachineInstrBuilder buildSetFPEnv(const SrcOp &Src)
Build and insert G_SET_FPENV Src.
MachineInstrBuilder buildPtrToInt(const DstOp &Dst, const SrcOp &Src)
Build and insert a G_PTRTOINT instruction.
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMetadata(const MDNode *MD) const
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addFPImm(const ConstantFP *Val) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
LLVM_ABI void copyIRFlags(const Instruction &I)
Copy all flags to MachineInst MIFlags.
static LLVM_ABI uint32_t copyFlagsFromInstruction(const Instruction &I)
LLVM_ABI void setDeactivationSymbol(MachineFunction &MF, Value *DS)
void setDebugLoc(DebugLoc DL)
Replace current source information with new such.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ 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.
static MachineOperand CreateES(const char *SymName, unsigned TargetFlags=0)
static MachineOperand CreateGA(const GlobalValue *GV, int64_t Offset, unsigned TargetFlags=0)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLT getType(Register Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register.
Records a mapping from an opaque lowering context to its LibcallLoweringInfo.
The optimization diagnostic interface.
Diagnostic information for missed-optimization remarks.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
Class to install both of the above.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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.
A BumpPtrAllocator that allows only elements of a specific type to be allocated.
Definition Allocator.h:397
Encapsulates all of the information needed to generate a stack protector check, and signals to isel w...
MachineBasicBlock * getSuccessMBB()
MachineBasicBlock * getFailureMBB()
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
SwitchLowering(FunctionLoweringInfo &funcinfo)
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Primary interface to the complete machine description for the target machine.
ExceptionHandling getExceptionModel() const
Return the ExceptionHandling to use.
const Triple & getTargetTriple() const
const Target & getTarget() const
unsigned NoTrapAfterNoreturn
Do not emit a trap instruction for 'unreachable' IR instructions behind noreturn calls,...
unsigned TrapUnreachable
Emit target-specific trap instruction for 'unreachable' IR instructions.
Target-Independent Code Generator Pass Configuration Options.
virtual std::unique_ptr< CSEConfigBase > getCSEConfig() const
Returns the CSEConfig object to use for the current optimization level.
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const CallLowering * getCallLowering() const
virtual const TargetLowering * getTargetLowering() const
bool isSPIRV() const
Tests whether the target is SPIR-V (32/64-bit/Logical).
Definition Triple.h:978
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getZero()
Definition TypeSize.h:345
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI bool isEmptyTy() const
Return true if this type is empty, that is, it has no elements or all of its elements are empty.
Definition Type.cpp:170
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:237
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition Type.h:314
bool isTokenTy() const
Return true if this is 'token'.
Definition Type.h:231
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
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
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:712
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
constexpr bool isZero() const
Definition TypeSize.h:153
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
A raw_ostream that writes to an std::string.
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
Offsets
Offsets in bytes from the start of the input buffer.
LLVM_ABI void sortAndRangeify(CaseClusterVector &Clusters)
Sort Clusters and merge adjacent cases.
std::vector< CaseCluster > CaseClusterVector
@ CC_Range
A cluster of adjacent case labels with the same destination, or just one case.
@ CC_JumpTable
A cluster of cases suitable for jump table lowering.
@ CC_BitTests
A cluster of cases suitable for bit test lowering.
SmallVector< SwitchWorkListItem, 4 > SwitchWorkList
CaseClusterVector::iterator CaseClusterIt
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
initializer< Ty > init(const Ty &Val)
ExceptionBehavior
Exception behavior used for floating point operations.
Definition FPEnv.h:39
@ ebIgnore
This corresponds to "fpexcept.ignore".
Definition FPEnv.h:40
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< CodeNode * > Code
Definition RDFGraph.h:388
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
@ Offset
Definition DWP.cpp:577
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Undef
Value of the register doesn't matter.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
LLVM_ABI void diagnoseDontCall(const CallInst &CI)
auto successors(const MachineBasicBlock *BB)
LLVM_ABI bool isExceptionPointerAndSelectorType(Type *Ty)
Return true if landingpad result type Ty is a struct of an exception pointer (pointer or integer) and...
Definition Analysis.cpp:201
LLVM_ABI MVT getMVTForLLT(LLT Ty)
Get a rough equivalent of an MVT for a given LLT.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
gep_type_iterator gep_type_end(const User *GEP)
LLVM_ABI MachineBasicBlock::iterator findSplitPointForStackProtector(MachineBasicBlock *BB, const TargetInstrInfo &TII)
Find the split point at which to splice the end of BB into its success stack protector check machine ...
LLVM_ABI LLT getLLTForMVT(MVT Ty)
Get a rough equivalent of an LLT for a given MVT.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI llvm::SmallVector< int, 16 > createStrideMask(unsigned Start, unsigned Stride, unsigned VF)
Create a stride shuffle mask.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI const LibcallLoweringInfo & getLibcallLowering(const ModuleLibcallLoweringInfo &ModuleInfo, const TargetSubtargetInfo &Subtarget)
Resolve the LibcallLoweringInfo for Subtarget from the module-level ModuleInfo, applying the subtarge...
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
generic_gep_type_iterator<> gep_type_iterator
auto succ_size(const MachineBasicBlock *BB)
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:227
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
@ Success
The lock was released successfully.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Global
Append to llvm.global_dtors.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
Definition Utils.cpp:1137
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2068
LLVM_ABI llvm::SmallVector< int, 16 > createInterleaveMask(unsigned VF, unsigned NumVecs)
Create an interleave shuffle mask.
@ FMul
Product of floats.
@ Sub
Subtraction of integers.
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
@ Default
Not specified; resolve to the target's default model.
Definition CodeGen.h:55
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI std::optional< RoundingMode > convertStrToRoundingMode(StringRef)
Returns a valid RoundingMode enumerator when given a string that is valid as input in constrained int...
Definition FPEnv.cpp:25
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI void computeValueLLTs(const DataLayout &DL, Type &Ty, SmallVectorImpl< LLT > &ValueLLTs, SmallVectorImpl< TypeSize > *Offsets=nullptr, TypeSize StartingOffset=TypeSize::getZero())
computeValueLLTs - Given an LLVM IR type, compute a sequence of LLTs that represent all the individua...
Definition Analysis.cpp:155
LLVM_ABI GlobalValue * ExtractTypeInfo(Value *V)
ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Definition Analysis.cpp:183
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
Align getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
Definition Local.h:240
LLVM_ABI LLT getLLTForType(Type &Ty, const DataLayout &DL)
Construct a low-level type based on an LLVM type.
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
Pair of physical register and lane mask.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:130
static bool canHandle(const Instruction *I, const TargetLibraryInfo &TLI)
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.
This structure is used to communicate between SelectionDAGBuilder and SDISel for the code generation ...
Register Reg
The virtual register containing the index of the jump table entry to jump to.
MachineBasicBlock * Default
The MBB of the default bb, which is a successor of the range check MBB.
unsigned JTI
The JumpTableIndex for this jump table in the function.
MachineBasicBlock * MBB
The MBB into which to emit the code for the indirect jump.