1 //===-- FastISel.h - Definition of the FastISel class ---*- C++ -*---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file defines the FastISel class.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CODEGEN_FASTISEL_H
16 #define LLVM_CODEGEN_FASTISEL_H
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/CodeGen/CallingConvLower.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/IR/CallingConv.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/Target/TargetLowering.h"
27 /// \brief This is a fast-path instruction selection class that generates poor
28 /// code and doesn't support illegal types or non-trivial lowering, but runs
46 : Val(nullptr), Ty(nullptr), IsSExt(false), IsZExt(false),
47 IsInReg(false), IsSRet(false), IsNest(false), IsByVal(false),
48 IsInAlloca(false), IsReturned(false), Alignment(0) {}
50 /// \brief Set CallLoweringInfo attribute flags based on a call instruction
51 /// and called function attributes.
52 void setAttributes(ImmutableCallSite *CS, unsigned AttrIdx);
54 typedef std::vector<ArgListEntry> ArgListTy;
56 struct CallLoweringInfo {
62 bool DoesNotReturn : 1;
63 bool IsReturnValueUsed : 1;
65 // \brief IsTailCall Should be modified by implementations of FastLowerCall
66 // that perform tail call conversions.
69 unsigned NumFixedArgs;
70 CallingConv::ID CallConv;
74 ImmutableCallSite *CS;
77 unsigned NumResultRegs;
81 SmallVector<Value *, 16> OutVals;
82 SmallVector<ISD::ArgFlagsTy, 16> OutFlags;
83 SmallVector<unsigned, 16> OutRegs;
84 SmallVector<ISD::InputArg, 4> Ins;
85 SmallVector<unsigned, 4> InRegs;
88 : RetTy(nullptr), RetSExt(false), RetZExt(false), IsVarArg(false),
89 IsInReg(false), DoesNotReturn(false), IsReturnValueUsed(true),
90 IsTailCall(false), NumFixedArgs(-1), CallConv(CallingConv::C),
91 Callee(nullptr), Symbol(nullptr), CS(nullptr), Call(nullptr),
92 ResultReg(0), NumResultRegs(0), IsPatchPoint(false) {}
94 CallLoweringInfo &setCallee(Type *ResultTy, FunctionType *FuncTy,
95 const Value *Target, ArgListTy &&ArgsList,
96 ImmutableCallSite &Call) {
100 IsInReg = Call.paramHasAttr(0, Attribute::InReg);
101 DoesNotReturn = Call.doesNotReturn();
102 IsVarArg = FuncTy->isVarArg();
103 IsReturnValueUsed = !Call.getInstruction()->use_empty();
104 RetSExt = Call.paramHasAttr(0, Attribute::SExt);
105 RetZExt = Call.paramHasAttr(0, Attribute::ZExt);
107 CallConv = Call.getCallingConv();
108 Args = std::move(ArgsList);
109 NumFixedArgs = FuncTy->getNumParams();
116 CallLoweringInfo &setCallee(Type *ResultTy, FunctionType *FuncTy,
117 MCSymbol *Target, ArgListTy &&ArgsList,
118 ImmutableCallSite &Call,
119 unsigned FixedArgs = ~0U) {
121 Callee = Call.getCalledValue();
124 IsInReg = Call.paramHasAttr(0, Attribute::InReg);
125 DoesNotReturn = Call.doesNotReturn();
126 IsVarArg = FuncTy->isVarArg();
127 IsReturnValueUsed = !Call.getInstruction()->use_empty();
128 RetSExt = Call.paramHasAttr(0, Attribute::SExt);
129 RetZExt = Call.paramHasAttr(0, Attribute::ZExt);
131 CallConv = Call.getCallingConv();
132 Args = std::move(ArgsList);
133 NumFixedArgs = (FixedArgs == ~0U) ? FuncTy->getNumParams() : FixedArgs;
140 CallLoweringInfo &setCallee(CallingConv::ID CC, Type *ResultTy,
141 const Value *Target, ArgListTy &&ArgsList,
142 unsigned FixedArgs = ~0U) {
146 Args = std::move(ArgsList);
147 NumFixedArgs = (FixedArgs == ~0U) ? Args.size() : FixedArgs;
151 CallLoweringInfo &setCallee(const DataLayout &DL, MCContext &Ctx,
152 CallingConv::ID CC, Type *ResultTy,
153 const char *Target, ArgListTy &&ArgsList,
154 unsigned FixedArgs = ~0U);
156 CallLoweringInfo &setCallee(CallingConv::ID CC, Type *ResultTy,
157 MCSymbol *Target, ArgListTy &&ArgsList,
158 unsigned FixedArgs = ~0U) {
162 Args = std::move(ArgsList);
163 NumFixedArgs = (FixedArgs == ~0U) ? Args.size() : FixedArgs;
167 CallLoweringInfo &setTailCall(bool Value = true) {
172 CallLoweringInfo &setIsPatchPoint(bool Value = true) {
173 IsPatchPoint = Value;
177 ArgListTy &getArgs() { return Args; }
192 DenseMap<const Value *, unsigned> LocalValueMap;
193 FunctionLoweringInfo &FuncInfo;
195 MachineRegisterInfo &MRI;
196 MachineFrameInfo &MFI;
197 MachineConstantPool &MCP;
199 const TargetMachine &TM;
200 const DataLayout &DL;
201 const TargetInstrInfo &TII;
202 const TargetLowering &TLI;
203 const TargetRegisterInfo &TRI;
204 const TargetLibraryInfo *LibInfo;
205 bool SkipTargetIndependentISel;
207 /// \brief The position of the last instruction for materializing constants
208 /// for use in the current block. It resets to EmitStartPt when it makes sense
209 /// (for example, it's usually profitable to avoid function calls between the
210 /// definition and the use)
211 MachineInstr *LastLocalValue;
213 /// \brief The top most instruction in the current block that is allowed for
214 /// emitting local variables. LastLocalValue resets to EmitStartPt when it
215 /// makes sense (for example, on function calls)
216 MachineInstr *EmitStartPt;
219 /// \brief Return the position of the last instruction emitted for
220 /// materializing constants for use in the current block.
221 MachineInstr *getLastLocalValue() { return LastLocalValue; }
223 /// \brief Update the position of the last instruction emitted for
224 /// materializing constants for use in the current block.
225 void setLastLocalValue(MachineInstr *I) {
230 /// \brief Set the current block to which generated machine instructions will
231 /// be appended, and clear the local CSE map.
232 void startNewBlock();
234 /// \brief Return current debug location information.
235 DebugLoc getCurDebugLoc() const { return DbgLoc; }
237 /// \brief Do "fast" instruction selection for function arguments and append
238 /// the machine instructions to the current block. Returns true when
240 bool lowerArguments();
242 /// \brief Do "fast" instruction selection for the given LLVM IR instruction
243 /// and append the generated machine instructions to the current block.
244 /// Returns true if selection was successful.
245 bool selectInstruction(const Instruction *I);
247 /// \brief Do "fast" instruction selection for the given LLVM IR operator
248 /// (Instruction or ConstantExpr), and append generated machine instructions
249 /// to the current block. Return true if selection was successful.
250 bool selectOperator(const User *I, unsigned Opcode);
252 /// \brief Create a virtual register and arrange for it to be assigned the
253 /// value for the given LLVM value.
254 unsigned getRegForValue(const Value *V);
256 /// \brief Look up the value to see if its value is already cached in a
257 /// register. It may be defined by instructions across blocks or defined
259 unsigned lookUpRegForValue(const Value *V);
261 /// \brief This is a wrapper around getRegForValue that also takes care of
262 /// truncating or sign-extending the given getelementptr index value.
263 std::pair<unsigned, bool> getRegForGEPIndex(const Value *V);
265 /// \brief We're checking to see if we can fold \p LI into \p FoldInst. Note
266 /// that we could have a sequence where multiple LLVM IR instructions are
267 /// folded into the same machineinstr. For example we could have:
269 /// A: x = load i32 *P
270 /// B: y = icmp A, 42
273 /// In this scenario, \p LI is "A", and \p FoldInst is "C". We know about "B"
274 /// (and any other folded instructions) because it is between A and C.
276 /// If we succeed folding, return true.
277 bool tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst);
279 /// \brief The specified machine instr operand is a vreg, and that vreg is
280 /// being provided by the specified load instruction. If possible, try to
281 /// fold the load as an operand to the instruction, returning true if
284 /// This method should be implemented by targets.
285 virtual bool tryToFoldLoadIntoMI(MachineInstr * /*MI*/, unsigned /*OpNo*/,
286 const LoadInst * /*LI*/) {
290 /// \brief Reset InsertPt to prepare for inserting instructions into the
292 void recomputeInsertPt();
294 /// \brief Remove all dead instructions between the I and E.
295 void removeDeadCode(MachineBasicBlock::iterator I,
296 MachineBasicBlock::iterator E);
299 MachineBasicBlock::iterator InsertPt;
303 /// \brief Prepare InsertPt to begin inserting instructions into the local
304 /// value area and return the old insert position.
305 SavePoint enterLocalValueArea();
307 /// \brief Reset InsertPt to the given old insert position.
308 void leaveLocalValueArea(SavePoint Old);
313 explicit FastISel(FunctionLoweringInfo &FuncInfo,
314 const TargetLibraryInfo *LibInfo,
315 bool SkipTargetIndependentISel = false);
317 /// \brief This method is called by target-independent code when the normal
318 /// FastISel process fails to select an instruction. This gives targets a
319 /// chance to emit code for anything that doesn't fit into FastISel's
320 /// framework. It returns true if it was successful.
321 virtual bool fastSelectInstruction(const Instruction *I) = 0;
323 /// \brief This method is called by target-independent code to do target-
324 /// specific argument lowering. It returns true if it was successful.
325 virtual bool fastLowerArguments();
327 /// \brief This method is called by target-independent code to do target-
328 /// specific call lowering. It returns true if it was successful.
329 virtual bool fastLowerCall(CallLoweringInfo &CLI);
331 /// \brief This method is called by target-independent code to do target-
332 /// specific intrinsic lowering. It returns true if it was successful.
333 virtual bool fastLowerIntrinsicCall(const IntrinsicInst *II);
335 /// \brief This method is called by target-independent code to request that an
336 /// instruction with the given type and opcode be emitted.
337 virtual unsigned fastEmit_(MVT VT, MVT RetVT, unsigned Opcode);
339 /// \brief This method is called by target-independent code to request that an
340 /// instruction with the given type, opcode, and register operand be emitted.
341 virtual unsigned fastEmit_r(MVT VT, MVT RetVT, unsigned Opcode, unsigned Op0,
344 /// \brief This method is called by target-independent code to request that an
345 /// instruction with the given type, opcode, and register operands be emitted.
346 virtual unsigned fastEmit_rr(MVT VT, MVT RetVT, unsigned Opcode, unsigned Op0,
347 bool Op0IsKill, unsigned Op1, bool Op1IsKill);
349 /// \brief This method is called by target-independent code to request that an
350 /// instruction with the given type, opcode, and register and immediate
351 // operands be emitted.
352 virtual unsigned fastEmit_ri(MVT VT, MVT RetVT, unsigned Opcode, unsigned Op0,
353 bool Op0IsKill, uint64_t Imm);
355 /// \brief This method is called by target-independent code to request that an
356 /// instruction with the given type, opcode, and register and floating-point
357 /// immediate operands be emitted.
358 virtual unsigned fastEmit_rf(MVT VT, MVT RetVT, unsigned Opcode, unsigned Op0,
359 bool Op0IsKill, const ConstantFP *FPImm);
361 /// \brief This method is called by target-independent code to request that an
362 /// instruction with the given type, opcode, and register and immediate
363 /// operands be emitted.
364 virtual unsigned fastEmit_rri(MVT VT, MVT RetVT, unsigned Opcode,
365 unsigned Op0, bool Op0IsKill, unsigned Op1,
366 bool Op1IsKill, uint64_t Imm);
368 /// \brief This method is a wrapper of fastEmit_ri.
370 /// It first tries to emit an instruction with an immediate operand using
371 /// fastEmit_ri. If that fails, it materializes the immediate into a register
372 /// and try fastEmit_rr instead.
373 unsigned fastEmit_ri_(MVT VT, unsigned Opcode, unsigned Op0, bool Op0IsKill,
374 uint64_t Imm, MVT ImmType);
376 /// \brief This method is called by target-independent code to request that an
377 /// instruction with the given type, opcode, and immediate operand be emitted.
378 virtual unsigned fastEmit_i(MVT VT, MVT RetVT, unsigned Opcode, uint64_t Imm);
380 /// \brief This method is called by target-independent code to request that an
381 /// instruction with the given type, opcode, and floating-point immediate
382 /// operand be emitted.
383 virtual unsigned fastEmit_f(MVT VT, MVT RetVT, unsigned Opcode,
384 const ConstantFP *FPImm);
386 /// \brief Emit a MachineInstr with no operands and a result register in the
387 /// given register class.
388 unsigned fastEmitInst_(unsigned MachineInstOpcode,
389 const TargetRegisterClass *RC);
391 /// \brief Emit a MachineInstr with one register operand and a result register
392 /// in the given register class.
393 unsigned fastEmitInst_r(unsigned MachineInstOpcode,
394 const TargetRegisterClass *RC, unsigned Op0,
397 /// \brief Emit a MachineInstr with two register operands and a result
398 /// register in the given register class.
399 unsigned fastEmitInst_rr(unsigned MachineInstOpcode,
400 const TargetRegisterClass *RC, unsigned Op0,
401 bool Op0IsKill, unsigned Op1, bool Op1IsKill);
403 /// \brief Emit a MachineInstr with three register operands and a result
404 /// register in the given register class.
405 unsigned fastEmitInst_rrr(unsigned MachineInstOpcode,
406 const TargetRegisterClass *RC, unsigned Op0,
407 bool Op0IsKill, unsigned Op1, bool Op1IsKill,
408 unsigned Op2, bool Op2IsKill);
410 /// \brief Emit a MachineInstr with a register operand, an immediate, and a
411 /// result register in the given register class.
412 unsigned fastEmitInst_ri(unsigned MachineInstOpcode,
413 const TargetRegisterClass *RC, unsigned Op0,
414 bool Op0IsKill, uint64_t Imm);
416 /// \brief Emit a MachineInstr with one register operand and two immediate
418 unsigned fastEmitInst_rii(unsigned MachineInstOpcode,
419 const TargetRegisterClass *RC, unsigned Op0,
420 bool Op0IsKill, uint64_t Imm1, uint64_t Imm2);
422 /// \brief Emit a MachineInstr with a floating point immediate, and a result
423 /// register in the given register class.
424 unsigned fastEmitInst_f(unsigned MachineInstOpcode,
425 const TargetRegisterClass *RC,
426 const ConstantFP *FPImm);
428 /// \brief Emit a MachineInstr with two register operands, an immediate, and a
429 /// result register in the given register class.
430 unsigned fastEmitInst_rri(unsigned MachineInstOpcode,
431 const TargetRegisterClass *RC, unsigned Op0,
432 bool Op0IsKill, unsigned Op1, bool Op1IsKill,
435 /// \brief Emit a MachineInstr with a single immediate operand, and a result
436 /// register in the given register class.
437 unsigned fastEmitInst_i(unsigned MachineInstrOpcode,
438 const TargetRegisterClass *RC, uint64_t Imm);
440 /// \brief Emit a MachineInstr for an extract_subreg from a specified index of
441 /// a superregister to a specified type.
442 unsigned fastEmitInst_extractsubreg(MVT RetVT, unsigned Op0, bool Op0IsKill,
445 /// \brief Emit MachineInstrs to compute the value of Op with all but the
446 /// least significant bit set to zero.
447 unsigned fastEmitZExtFromI1(MVT VT, unsigned Op0, bool Op0IsKill);
449 /// \brief Emit an unconditional branch to the given block, unless it is the
450 /// immediate (fall-through) successor, and update the CFG.
451 void fastEmitBranch(MachineBasicBlock *MBB, DebugLoc DL);
453 /// Emit an unconditional branch to \p FalseMBB, obtains the branch weight
454 /// and adds TrueMBB and FalseMBB to the successor list.
455 void finishCondBranch(const BasicBlock *BranchBB, MachineBasicBlock *TrueMBB,
456 MachineBasicBlock *FalseMBB);
458 /// \brief Update the value map to include the new mapping for this
459 /// instruction, or insert an extra copy to get the result in a previous
460 /// determined register.
462 /// NOTE: This is only necessary because we might select a block that uses a
463 /// value before we select the block that defines the value. It might be
464 /// possible to fix this by selecting blocks in reverse postorder.
465 void updateValueMap(const Value *I, unsigned Reg, unsigned NumRegs = 1);
467 unsigned createResultReg(const TargetRegisterClass *RC);
469 /// \brief Try to constrain Op so that it is usable by argument OpNum of the
470 /// provided MCInstrDesc. If this fails, create a new virtual register in the
471 /// correct class and COPY the value there.
472 unsigned constrainOperandRegClass(const MCInstrDesc &II, unsigned Op,
475 /// \brief Emit a constant in a register using target-specific logic, such as
476 /// constant pool loads.
477 virtual unsigned fastMaterializeConstant(const Constant *C) { return 0; }
479 /// \brief Emit an alloca address in a register using target-specific logic.
480 virtual unsigned fastMaterializeAlloca(const AllocaInst *C) { return 0; }
482 /// \brief Emit the floating-point constant +0.0 in a register using target-
484 virtual unsigned fastMaterializeFloatZero(const ConstantFP *CF) {
488 /// \brief Check if \c Add is an add that can be safely folded into \c GEP.
490 /// \c Add can be folded into \c GEP if:
491 /// - \c Add is an add,
492 /// - \c Add's size matches \c GEP's,
493 /// - \c Add is in the same basic block as \c GEP, and
494 /// - \c Add has a constant operand.
495 bool canFoldAddIntoGEP(const User *GEP, const Value *Add);
497 /// \brief Test whether the given value has exactly one use.
498 bool hasTrivialKill(const Value *V);
500 /// \brief Create a machine mem operand from the given instruction.
501 MachineMemOperand *createMachineMemOperandFor(const Instruction *I) const;
503 CmpInst::Predicate optimizeCmpPredicate(const CmpInst *CI) const;
505 bool lowerCallTo(const CallInst *CI, MCSymbol *Symbol, unsigned NumArgs);
506 bool lowerCallTo(const CallInst *CI, const char *SymbolName,
508 bool lowerCallTo(CallLoweringInfo &CLI);
510 bool isCommutativeIntrinsic(IntrinsicInst const *II) {
511 switch (II->getIntrinsicID()) {
512 case Intrinsic::sadd_with_overflow:
513 case Intrinsic::uadd_with_overflow:
514 case Intrinsic::smul_with_overflow:
515 case Intrinsic::umul_with_overflow:
523 bool lowerCall(const CallInst *I);
524 /// \brief Select and emit code for a binary operator instruction, which has
525 /// an opcode which directly corresponds to the given ISD opcode.
526 bool selectBinaryOp(const User *I, unsigned ISDOpcode);
527 bool selectFNeg(const User *I);
528 bool selectGetElementPtr(const User *I);
529 bool selectStackmap(const CallInst *I);
530 bool selectPatchpoint(const CallInst *I);
531 bool selectCall(const User *Call);
532 bool selectIntrinsicCall(const IntrinsicInst *II);
533 bool selectBitCast(const User *I);
534 bool selectCast(const User *I, unsigned Opcode);
535 bool selectExtractValue(const User *I);
536 bool selectInsertValue(const User *I);
539 /// \brief Handle PHI nodes in successor blocks.
541 /// Emit code to ensure constants are copied into registers when needed.
542 /// Remember the virtual registers that need to be added to the Machine PHI
543 /// nodes as input. We cannot just directly add them, because expansion might
544 /// result in multiple MBB's for one BB. As such, the start of the BB might
545 /// correspond to a different MBB than the end.
546 bool handlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB);
548 /// \brief Helper for materializeRegForValue to materialize a constant in a
549 /// target-independent way.
550 unsigned materializeConstant(const Value *V, MVT VT);
552 /// \brief Helper for getRegForVale. This function is called when the value
553 /// isn't already available in a register and must be materialized with new
555 unsigned materializeRegForValue(const Value *V, MVT VT);
557 /// \brief Clears LocalValueMap and moves the area for the new local variables
558 /// to the beginning of the block. It helps to avoid spilling cached variables
559 /// across heavy instructions like calls.
560 void flushLocalValueMap();
562 /// \brief Insertion point before trying to select the current instruction.
563 MachineBasicBlock::iterator SavedInsertPt;
565 /// \brief Add a stackmap or patchpoint intrinsic call's live variable
566 /// operands to a stackmap or patchpoint machine instruction.
567 bool addStackMapLiveVars(SmallVectorImpl<MachineOperand> &Ops,
568 const CallInst *CI, unsigned StartIdx);
569 bool lowerCallOperands(const CallInst *CI, unsigned ArgIdx, unsigned NumArgs,
570 const Value *Callee, bool ForceRetVoidTy,
571 CallLoweringInfo &CLI);
574 } // end namespace llvm