1 //===-- SelectionDAGBuild.h - Selection-DAG building ----------------------===//
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 //===----------------------------------------------------------------------===//
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
12 //===----------------------------------------------------------------------===//
14 #ifndef SELECTIONDAGBUILD_H
15 #define SELECTIONDAGBUILD_H
17 #include "llvm/Constants.h"
18 #include "llvm/CodeGen/SelectionDAG.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/CodeGen/SelectionDAGNodes.h"
25 #include "llvm/CodeGen/ValueTypes.h"
26 #include "llvm/Support/CallSite.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Target/TargetMachine.h"
40 class ExtractElementInst;
41 class ExtractValueInst;
49 class GetElementPtrInst;
54 class InsertElementInst;
55 class InsertValueInst;
58 class MachineBasicBlock;
59 class MachineFunction;
61 class MachineModuleInfo;
62 class MachineRegisterInfo;
66 class SDISelAsmOperandInfo;
69 class ShuffleVectorInst;
77 class UnreachableInst;
82 //===--------------------------------------------------------------------===//
83 /// FunctionLoweringInfo - This contains information that is global to a
84 /// function that is used when lowering a region of the function.
86 class FunctionLoweringInfo {
91 MachineRegisterInfo *RegInfo;
93 explicit FunctionLoweringInfo(TargetLowering &TLI);
95 /// set - Initialize this FunctionLoweringInfo with the given Function
96 /// and its associated MachineFunction.
98 void set(Function &Fn, MachineFunction &MF, SelectionDAG &DAG,
101 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
102 DenseMap<const BasicBlock*, MachineBasicBlock *> MBBMap;
104 /// ValueMap - Since we emit code for the function a basic block at a time,
105 /// we must remember which virtual registers hold the values for
106 /// cross-basic-block values.
107 DenseMap<const Value*, unsigned> ValueMap;
109 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
110 /// the entry block. This allows the allocas to be efficiently referenced
111 /// anywhere in the function.
112 DenseMap<const AllocaInst*, int> StaticAllocaMap;
115 SmallSet<Instruction*, 8> CatchInfoLost;
116 SmallSet<Instruction*, 8> CatchInfoFound;
119 unsigned MakeReg(EVT VT);
121 /// isExportedInst - Return true if the specified value is an instruction
122 /// exported from its block.
123 bool isExportedInst(const Value *V) {
124 return ValueMap.count(V);
127 unsigned CreateRegForValue(const Value *V);
129 unsigned InitializeRegForValue(const Value *V) {
130 unsigned &R = ValueMap[V];
131 assert(R == 0 && "Already initialized this value register!");
132 return R = CreateRegForValue(V);
136 unsigned NumSignBits;
137 APInt KnownOne, KnownZero;
138 LiveOutInfo() : NumSignBits(0), KnownOne(1, 0), KnownZero(1, 0) {}
141 /// LiveOutRegInfo - Information about live out vregs, indexed by their
142 /// register number offset by 'FirstVirtualRegister'.
143 std::vector<LiveOutInfo> LiveOutRegInfo;
145 /// clear - Clear out all the function-specific state. This returns this
146 /// FunctionLoweringInfo to an empty state, ready to be used for a
147 /// different function.
151 StaticAllocaMap.clear();
153 CatchInfoLost.clear();
154 CatchInfoFound.clear();
156 LiveOutRegInfo.clear();
160 //===----------------------------------------------------------------------===//
161 /// SelectionDAGLowering - This is the common target-independent lowering
162 /// implementation that is parameterized by a TargetLowering object.
163 /// Also, targets can overload any lowering method.
165 class SelectionDAGLowering {
166 MachineBasicBlock *CurMBB;
168 /// CurDebugLoc - current file + line number. Changes as we build the DAG.
169 DebugLoc CurDebugLoc;
171 DenseMap<const Value*, SDValue> NodeMap;
173 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
174 /// them up and then emit token factor nodes when possible. This allows us to
175 /// get simple disambiguation between loads without worrying about alias
177 SmallVector<SDValue, 8> PendingLoads;
179 /// PendingExports - CopyToReg nodes that copy values to virtual registers
180 /// for export to other blocks need to be emitted before any terminator
181 /// instruction, but they have no other ordering requirements. We bunch them
182 /// up and the emit a single tokenfactor for them just before terminator
184 SmallVector<SDValue, 8> PendingExports;
186 /// Case - A struct to record the Value for a switch case, and the
187 /// case's target basic block.
191 MachineBasicBlock* BB;
193 Case() : Low(0), High(0), BB(0) { }
194 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
195 Low(low), High(high), BB(bb) { }
196 uint64_t size() const {
197 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
198 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
199 return (rHigh - rLow + 1ULL);
205 MachineBasicBlock* BB;
208 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
209 Mask(mask), BB(bb), Bits(bits) { }
212 typedef std::vector<Case> CaseVector;
213 typedef std::vector<CaseBits> CaseBitsVector;
214 typedef CaseVector::iterator CaseItr;
215 typedef std::pair<CaseItr, CaseItr> CaseRange;
217 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
218 /// of conditional branches.
220 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
221 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
223 /// CaseBB - The MBB in which to emit the compare and branch
224 MachineBasicBlock *CaseBB;
225 /// LT, GE - If nonzero, we know the current case value must be less-than or
226 /// greater-than-or-equal-to these Constants.
229 /// Range - A pair of iterators representing the range of case values to be
230 /// processed at this point in the binary search tree.
234 typedef std::vector<CaseRec> CaseRecVector;
236 /// The comparison function for sorting the switch case values in the vector.
237 /// WARNING: Case ranges should be disjoint!
239 bool operator () (const Case& C1, const Case& C2) {
240 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
241 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
242 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
243 return CI1->getValue().slt(CI2->getValue());
248 bool operator () (const CaseBits& C1, const CaseBits& C2) {
249 return C1.Bits > C2.Bits;
253 size_t Clusterify(CaseVector& Cases, const SwitchInst &SI);
255 /// CaseBlock - This structure is used to communicate between SDLowering and
256 /// SDISel for the code generation of additional basic blocks needed by multi-
257 /// case switch statements.
259 CaseBlock(ISD::CondCode cc, Value *cmplhs, Value *cmprhs, Value *cmpmiddle,
260 MachineBasicBlock *truebb, MachineBasicBlock *falsebb,
261 MachineBasicBlock *me)
262 : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
263 TrueBB(truebb), FalseBB(falsebb), ThisBB(me) {}
264 // CC - the condition code to use for the case block's setcc node
266 // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
267 // Emit by default LHS op RHS. MHS is used for range comparisons:
268 // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
269 Value *CmpLHS, *CmpMHS, *CmpRHS;
270 // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
271 MachineBasicBlock *TrueBB, *FalseBB;
272 // ThisBB - the block into which to emit the code for the setcc and branches
273 MachineBasicBlock *ThisBB;
276 JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
277 MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
279 /// Reg - the virtual register containing the index of the jump table entry
282 /// JTI - the JumpTableIndex for this jump table in the function.
284 /// MBB - the MBB into which to emit the code for the indirect jump.
285 MachineBasicBlock *MBB;
286 /// Default - the MBB of the default bb, which is a successor of the range
287 /// check MBB. This is when updating PHI nodes in successors.
288 MachineBasicBlock *Default;
290 struct JumpTableHeader {
291 JumpTableHeader(APInt F, APInt L, Value* SV, MachineBasicBlock* H,
293 First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
297 MachineBasicBlock *HeaderBB;
300 typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
303 BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr):
304 Mask(M), ThisBB(T), TargetBB(Tr) { }
306 MachineBasicBlock* ThisBB;
307 MachineBasicBlock* TargetBB;
310 typedef SmallVector<BitTestCase, 3> BitTestInfo;
312 struct BitTestBlock {
313 BitTestBlock(APInt F, APInt R, Value* SV,
315 MachineBasicBlock* P, MachineBasicBlock* D,
316 const BitTestInfo& C):
317 First(F), Range(R), SValue(SV), Reg(Rg), Emitted(E),
318 Parent(P), Default(D), Cases(C) { }
324 MachineBasicBlock *Parent;
325 MachineBasicBlock *Default;
330 // TLI - This is information that describes the available target features we
331 // need for lowering. This indicates when operations are unavailable,
332 // implemented with a libcall, etc.
335 const TargetData *TD;
338 /// SwitchCases - Vector of CaseBlock structures used to communicate
339 /// SwitchInst code generation information.
340 std::vector<CaseBlock> SwitchCases;
341 /// JTCases - Vector of JumpTable structures used to communicate
342 /// SwitchInst code generation information.
343 std::vector<JumpTableBlock> JTCases;
344 /// BitTestCases - Vector of BitTestBlock structures used to communicate
345 /// SwitchInst code generation information.
346 std::vector<BitTestBlock> BitTestCases;
348 /// PHINodesToUpdate - A list of phi instructions whose operand list will
349 /// be updated after processing the current basic block.
350 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
352 /// EdgeMapping - If an edge from CurMBB to any MBB is changed (e.g. due to
353 /// scheduler custom lowering), track the change here.
354 DenseMap<MachineBasicBlock*, MachineBasicBlock*> EdgeMapping;
356 // Emit PHI-node-operand constants only once even if used by multiple
358 DenseMap<Constant*, unsigned> ConstantsOut;
360 /// FuncInfo - Information about the function as a whole.
362 FunctionLoweringInfo &FuncInfo;
364 /// OptLevel - What optimization level we're generating code for.
366 CodeGenOpt::Level OptLevel;
368 /// GFI - Garbage collection metadata for the function.
371 /// HasTailCall - This is set to true if a call in the current
372 /// block has been translated as a tail call. In this case,
373 /// no subsequent DAG nodes should be created.
377 LLVMContext *Context;
379 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
380 FunctionLoweringInfo &funcinfo,
381 CodeGenOpt::Level ol)
382 : CurDebugLoc(DebugLoc::getUnknownLoc()),
383 TLI(tli), DAG(dag), FuncInfo(funcinfo), OptLevel(ol),
385 Context(dag.getContext()) {
388 void init(GCFunctionInfo *gfi, AliasAnalysis &aa);
390 /// clear - Clear out the curret SelectionDAG and the associated
391 /// state and prepare this SelectionDAGLowering object to be used
392 /// for a new block. This doesn't clear out information about
393 /// additional blocks that are needed to complete switch lowering
394 /// or PHI node updating; that information is cleared out as it is
398 /// getRoot - Return the current virtual root of the Selection DAG,
399 /// flushing any PendingLoad items. This must be done before emitting
400 /// a store or any other node that may need to be ordered after any
401 /// prior load instructions.
405 /// getControlRoot - Similar to getRoot, but instead of flushing all the
406 /// PendingLoad items, flush all the PendingExports items. It is necessary
407 /// to do this before emitting a terminator instruction.
409 SDValue getControlRoot();
411 DebugLoc getCurDebugLoc() const { return CurDebugLoc; }
412 void setCurDebugLoc(DebugLoc dl) { CurDebugLoc = dl; }
414 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
416 void visit(Instruction &I);
418 void visit(unsigned Opcode, User &I);
420 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
422 SDValue getValue(const Value *V);
424 void setValue(const Value *V, SDValue NewN) {
425 SDValue &N = NodeMap[V];
426 assert(N.getNode() == 0 && "Already set a value for this node!");
430 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
431 std::set<unsigned> &OutputRegs,
432 std::set<unsigned> &InputRegs);
434 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
435 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
437 void EmitBranchForMergedCondition(Value *Cond, MachineBasicBlock *TBB,
438 MachineBasicBlock *FBB,
439 MachineBasicBlock *CurBB);
440 bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases);
441 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
442 void CopyToExportRegsIfNeeded(Value *V);
443 void ExportFromCurrentBlock(Value *V);
444 void LowerCallTo(CallSite CS, SDValue Callee, bool IsTailCall,
445 MachineBasicBlock *LandingPad = NULL);
448 // Terminator instructions.
449 void visitRet(ReturnInst &I);
450 void visitBr(BranchInst &I);
451 void visitSwitch(SwitchInst &I);
452 void visitUnreachable(UnreachableInst &I) { /* noop */ }
454 // Helpers for visitSwitch
455 bool handleSmallSwitchRange(CaseRec& CR,
456 CaseRecVector& WorkList,
458 MachineBasicBlock* Default);
459 bool handleJTSwitchCase(CaseRec& CR,
460 CaseRecVector& WorkList,
462 MachineBasicBlock* Default);
463 bool handleBTSplitSwitchCase(CaseRec& CR,
464 CaseRecVector& WorkList,
466 MachineBasicBlock* Default);
467 bool handleBitTestsSwitchCase(CaseRec& CR,
468 CaseRecVector& WorkList,
470 MachineBasicBlock* Default);
472 void visitSwitchCase(CaseBlock &CB);
473 void visitBitTestHeader(BitTestBlock &B);
474 void visitBitTestCase(MachineBasicBlock* NextMBB,
477 void visitJumpTable(JumpTable &JT);
478 void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH);
481 // These all get lowered before this pass.
482 void visitInvoke(InvokeInst &I);
483 void visitUnwind(UnwindInst &I);
485 void visitBinary(User &I, unsigned OpCode);
486 void visitShift(User &I, unsigned Opcode);
487 void visitAdd(User &I) { visitBinary(I, ISD::ADD); }
488 void visitFAdd(User &I) { visitBinary(I, ISD::FADD); }
489 void visitSub(User &I) { visitBinary(I, ISD::SUB); }
490 void visitFSub(User &I);
491 void visitMul(User &I) { visitBinary(I, ISD::MUL); }
492 void visitFMul(User &I) { visitBinary(I, ISD::FMUL); }
493 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
494 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
495 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
496 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
497 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
498 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
499 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
500 void visitOr (User &I) { visitBinary(I, ISD::OR); }
501 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
502 void visitShl (User &I) { visitShift(I, ISD::SHL); }
503 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
504 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
505 void visitICmp(User &I);
506 void visitFCmp(User &I);
507 // Visit the conversion instructions
508 void visitTrunc(User &I);
509 void visitZExt(User &I);
510 void visitSExt(User &I);
511 void visitFPTrunc(User &I);
512 void visitFPExt(User &I);
513 void visitFPToUI(User &I);
514 void visitFPToSI(User &I);
515 void visitUIToFP(User &I);
516 void visitSIToFP(User &I);
517 void visitPtrToInt(User &I);
518 void visitIntToPtr(User &I);
519 void visitBitCast(User &I);
521 void visitExtractElement(User &I);
522 void visitInsertElement(User &I);
523 void visitShuffleVector(User &I);
525 void visitExtractValue(ExtractValueInst &I);
526 void visitInsertValue(InsertValueInst &I);
528 void visitGetElementPtr(User &I);
529 void visitSelect(User &I);
531 void visitFree(FreeInst &I);
532 void visitAlloca(AllocaInst &I);
533 void visitLoad(LoadInst &I);
534 void visitStore(StoreInst &I);
535 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
536 void visitCall(CallInst &I);
537 void visitInlineAsm(CallSite CS);
538 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
539 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
541 void visitPow(CallInst &I);
542 void visitExp2(CallInst &I);
543 void visitExp(CallInst &I);
544 void visitLog(CallInst &I);
545 void visitLog2(CallInst &I);
546 void visitLog10(CallInst &I);
548 void visitVAStart(CallInst &I);
549 void visitVAArg(VAArgInst &I);
550 void visitVAEnd(CallInst &I);
551 void visitVACopy(CallInst &I);
553 void visitUserOp1(Instruction &I) {
554 llvm_unreachable("UserOp1 should not exist at instruction selection time!");
556 void visitUserOp2(Instruction &I) {
557 llvm_unreachable("UserOp2 should not exist at instruction selection time!");
560 const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
561 const char *implVisitAluOverflow(CallInst &I, ISD::NodeType Op);
564 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
565 /// call, and add them to the specified machine basic block.
566 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
567 MachineBasicBlock *MBB);
569 } // end namespace llvm