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;
48 class FunctionLoweringInfo;
49 class GetElementPtrInst;
55 class InsertElementInst;
56 class InsertValueInst;
59 class MachineBasicBlock;
60 class MachineFunction;
62 class MachineModuleInfo;
63 class MachineRegisterInfo;
67 class SDISelAsmOperandInfo;
70 class ShuffleVectorInst;
78 class UnreachableInst;
83 //===----------------------------------------------------------------------===//
84 /// SelectionDAGLowering - This is the common target-independent lowering
85 /// implementation that is parameterized by a TargetLowering object.
86 /// Also, targets can overload any lowering method.
88 class SelectionDAGLowering {
89 MachineBasicBlock *CurMBB;
91 /// CurDebugLoc - current file + line number. Changes as we build the DAG.
94 DenseMap<const Value*, SDValue> NodeMap;
96 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
97 /// them up and then emit token factor nodes when possible. This allows us to
98 /// get simple disambiguation between loads without worrying about alias
100 SmallVector<SDValue, 8> PendingLoads;
102 /// PendingExports - CopyToReg nodes that copy values to virtual registers
103 /// for export to other blocks need to be emitted before any terminator
104 /// instruction, but they have no other ordering requirements. We bunch them
105 /// up and the emit a single tokenfactor for them just before terminator
107 SmallVector<SDValue, 8> PendingExports;
109 /// Case - A struct to record the Value for a switch case, and the
110 /// case's target basic block.
114 MachineBasicBlock* BB;
116 Case() : Low(0), High(0), BB(0) { }
117 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
118 Low(low), High(high), BB(bb) { }
120 const APInt &rHigh = cast<ConstantInt>(High)->getValue();
121 const APInt &rLow = cast<ConstantInt>(Low)->getValue();
122 return (rHigh - rLow + 1ULL);
128 MachineBasicBlock* BB;
131 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
132 Mask(mask), BB(bb), Bits(bits) { }
135 typedef std::vector<Case> CaseVector;
136 typedef std::vector<CaseBits> CaseBitsVector;
137 typedef CaseVector::iterator CaseItr;
138 typedef std::pair<CaseItr, CaseItr> CaseRange;
140 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
141 /// of conditional branches.
143 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
144 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
146 /// CaseBB - The MBB in which to emit the compare and branch
147 MachineBasicBlock *CaseBB;
148 /// LT, GE - If nonzero, we know the current case value must be less-than or
149 /// greater-than-or-equal-to these Constants.
152 /// Range - A pair of iterators representing the range of case values to be
153 /// processed at this point in the binary search tree.
157 typedef std::vector<CaseRec> CaseRecVector;
159 /// The comparison function for sorting the switch case values in the vector.
160 /// WARNING: Case ranges should be disjoint!
162 bool operator () (const Case& C1, const Case& C2) {
163 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
164 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
165 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
166 return CI1->getValue().slt(CI2->getValue());
171 bool operator () (const CaseBits& C1, const CaseBits& C2) {
172 return C1.Bits > C2.Bits;
176 size_t Clusterify(CaseVector& Cases, const SwitchInst &SI);
178 /// CaseBlock - This structure is used to communicate between SDLowering and
179 /// SDISel for the code generation of additional basic blocks needed by multi-
180 /// case switch statements.
182 CaseBlock(ISD::CondCode cc, Value *cmplhs, Value *cmprhs, Value *cmpmiddle,
183 MachineBasicBlock *truebb, MachineBasicBlock *falsebb,
184 MachineBasicBlock *me)
185 : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
186 TrueBB(truebb), FalseBB(falsebb), ThisBB(me) {}
187 // CC - the condition code to use for the case block's setcc node
189 // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
190 // Emit by default LHS op RHS. MHS is used for range comparisons:
191 // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
192 Value *CmpLHS, *CmpMHS, *CmpRHS;
193 // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
194 MachineBasicBlock *TrueBB, *FalseBB;
195 // ThisBB - the block into which to emit the code for the setcc and branches
196 MachineBasicBlock *ThisBB;
199 JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
200 MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
202 /// Reg - the virtual register containing the index of the jump table entry
205 /// JTI - the JumpTableIndex for this jump table in the function.
207 /// MBB - the MBB into which to emit the code for the indirect jump.
208 MachineBasicBlock *MBB;
209 /// Default - the MBB of the default bb, which is a successor of the range
210 /// check MBB. This is when updating PHI nodes in successors.
211 MachineBasicBlock *Default;
213 struct JumpTableHeader {
214 JumpTableHeader(APInt F, APInt L, Value* SV, MachineBasicBlock* H,
216 First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
220 MachineBasicBlock *HeaderBB;
223 typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
226 BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr):
227 Mask(M), ThisBB(T), TargetBB(Tr) { }
229 MachineBasicBlock* ThisBB;
230 MachineBasicBlock* TargetBB;
233 typedef SmallVector<BitTestCase, 3> BitTestInfo;
235 struct BitTestBlock {
236 BitTestBlock(APInt F, APInt R, Value* SV,
238 MachineBasicBlock* P, MachineBasicBlock* D,
239 const BitTestInfo& C):
240 First(F), Range(R), SValue(SV), Reg(Rg), Emitted(E),
241 Parent(P), Default(D), Cases(C) { }
247 MachineBasicBlock *Parent;
248 MachineBasicBlock *Default;
253 // TLI - This is information that describes the available target features we
254 // need for lowering. This indicates when operations are unavailable,
255 // implemented with a libcall, etc.
258 const TargetData *TD;
261 /// SwitchCases - Vector of CaseBlock structures used to communicate
262 /// SwitchInst code generation information.
263 std::vector<CaseBlock> SwitchCases;
264 /// JTCases - Vector of JumpTable structures used to communicate
265 /// SwitchInst code generation information.
266 std::vector<JumpTableBlock> JTCases;
267 /// BitTestCases - Vector of BitTestBlock structures used to communicate
268 /// SwitchInst code generation information.
269 std::vector<BitTestBlock> BitTestCases;
271 /// PHINodesToUpdate - A list of phi instructions whose operand list will
272 /// be updated after processing the current basic block.
273 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
275 /// EdgeMapping - If an edge from CurMBB to any MBB is changed (e.g. due to
276 /// scheduler custom lowering), track the change here.
277 DenseMap<MachineBasicBlock*, MachineBasicBlock*> EdgeMapping;
279 // Emit PHI-node-operand constants only once even if used by multiple
281 DenseMap<Constant*, unsigned> ConstantsOut;
283 /// FuncInfo - Information about the function as a whole.
285 FunctionLoweringInfo &FuncInfo;
287 /// OptLevel - What optimization level we're generating code for.
289 CodeGenOpt::Level OptLevel;
291 /// GFI - Garbage collection metadata for the function.
294 /// HasTailCall - This is set to true if a call in the current
295 /// block has been translated as a tail call. In this case,
296 /// no subsequent DAG nodes should be created.
300 LLVMContext *Context;
302 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
303 FunctionLoweringInfo &funcinfo,
304 CodeGenOpt::Level ol)
305 : CurDebugLoc(DebugLoc::getUnknownLoc()),
306 TLI(tli), DAG(dag), FuncInfo(funcinfo), OptLevel(ol),
308 Context(dag.getContext()) {
311 void init(GCFunctionInfo *gfi, AliasAnalysis &aa);
313 /// clear - Clear out the curret SelectionDAG and the associated
314 /// state and prepare this SelectionDAGLowering object to be used
315 /// for a new block. This doesn't clear out information about
316 /// additional blocks that are needed to complete switch lowering
317 /// or PHI node updating; that information is cleared out as it is
321 /// getRoot - Return the current virtual root of the Selection DAG,
322 /// flushing any PendingLoad items. This must be done before emitting
323 /// a store or any other node that may need to be ordered after any
324 /// prior load instructions.
328 /// getControlRoot - Similar to getRoot, but instead of flushing all the
329 /// PendingLoad items, flush all the PendingExports items. It is necessary
330 /// to do this before emitting a terminator instruction.
332 SDValue getControlRoot();
334 DebugLoc getCurDebugLoc() const { return CurDebugLoc; }
335 void setCurDebugLoc(DebugLoc dl) { CurDebugLoc = dl; }
337 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
339 void visit(Instruction &I);
341 void visit(unsigned Opcode, User &I);
343 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
345 SDValue getValue(const Value *V);
347 void setValue(const Value *V, SDValue NewN) {
348 SDValue &N = NodeMap[V];
349 assert(N.getNode() == 0 && "Already set a value for this node!");
353 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
354 std::set<unsigned> &OutputRegs,
355 std::set<unsigned> &InputRegs);
357 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
358 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
360 void EmitBranchForMergedCondition(Value *Cond, MachineBasicBlock *TBB,
361 MachineBasicBlock *FBB,
362 MachineBasicBlock *CurBB);
363 bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases);
364 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
365 void CopyToExportRegsIfNeeded(Value *V);
366 void ExportFromCurrentBlock(Value *V);
367 void LowerCallTo(CallSite CS, SDValue Callee, bool IsTailCall,
368 MachineBasicBlock *LandingPad = NULL);
371 // Terminator instructions.
372 void visitRet(ReturnInst &I);
373 void visitBr(BranchInst &I);
374 void visitSwitch(SwitchInst &I);
375 void visitIndirectBr(IndirectBrInst &I);
376 void visitUnreachable(UnreachableInst &I) { /* noop */ }
378 // Helpers for visitSwitch
379 bool handleSmallSwitchRange(CaseRec& CR,
380 CaseRecVector& WorkList,
382 MachineBasicBlock* Default);
383 bool handleJTSwitchCase(CaseRec& CR,
384 CaseRecVector& WorkList,
386 MachineBasicBlock* Default);
387 bool handleBTSplitSwitchCase(CaseRec& CR,
388 CaseRecVector& WorkList,
390 MachineBasicBlock* Default);
391 bool handleBitTestsSwitchCase(CaseRec& CR,
392 CaseRecVector& WorkList,
394 MachineBasicBlock* Default);
396 void visitSwitchCase(CaseBlock &CB);
397 void visitBitTestHeader(BitTestBlock &B);
398 void visitBitTestCase(MachineBasicBlock* NextMBB,
401 void visitJumpTable(JumpTable &JT);
402 void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH);
405 // These all get lowered before this pass.
406 void visitInvoke(InvokeInst &I);
407 void visitUnwind(UnwindInst &I);
409 void visitBinary(User &I, unsigned OpCode);
410 void visitShift(User &I, unsigned Opcode);
411 void visitAdd(User &I) { visitBinary(I, ISD::ADD); }
412 void visitFAdd(User &I) { visitBinary(I, ISD::FADD); }
413 void visitSub(User &I) { visitBinary(I, ISD::SUB); }
414 void visitFSub(User &I);
415 void visitMul(User &I) { visitBinary(I, ISD::MUL); }
416 void visitFMul(User &I) { visitBinary(I, ISD::FMUL); }
417 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
418 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
419 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
420 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
421 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
422 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
423 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
424 void visitOr (User &I) { visitBinary(I, ISD::OR); }
425 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
426 void visitShl (User &I) { visitShift(I, ISD::SHL); }
427 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
428 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
429 void visitICmp(User &I);
430 void visitFCmp(User &I);
431 // Visit the conversion instructions
432 void visitTrunc(User &I);
433 void visitZExt(User &I);
434 void visitSExt(User &I);
435 void visitFPTrunc(User &I);
436 void visitFPExt(User &I);
437 void visitFPToUI(User &I);
438 void visitFPToSI(User &I);
439 void visitUIToFP(User &I);
440 void visitSIToFP(User &I);
441 void visitPtrToInt(User &I);
442 void visitIntToPtr(User &I);
443 void visitBitCast(User &I);
445 void visitExtractElement(User &I);
446 void visitInsertElement(User &I);
447 void visitShuffleVector(User &I);
449 void visitExtractValue(ExtractValueInst &I);
450 void visitInsertValue(InsertValueInst &I);
452 void visitGetElementPtr(User &I);
453 void visitSelect(User &I);
455 void visitAlloca(AllocaInst &I);
456 void visitLoad(LoadInst &I);
457 void visitStore(StoreInst &I);
458 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
459 void visitCall(CallInst &I);
460 void visitInlineAsm(CallSite CS);
461 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
462 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
464 void visitPow(CallInst &I);
465 void visitExp2(CallInst &I);
466 void visitExp(CallInst &I);
467 void visitLog(CallInst &I);
468 void visitLog2(CallInst &I);
469 void visitLog10(CallInst &I);
471 void visitVAStart(CallInst &I);
472 void visitVAArg(VAArgInst &I);
473 void visitVAEnd(CallInst &I);
474 void visitVACopy(CallInst &I);
476 void visitUserOp1(Instruction &I) {
477 llvm_unreachable("UserOp1 should not exist at instruction selection time!");
479 void visitUserOp2(Instruction &I) {
480 llvm_unreachable("UserOp2 should not exist at instruction selection time!");
483 const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
484 const char *implVisitAluOverflow(CallInst &I, ISD::NodeType Op);
487 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
488 /// call, and add them to the specified machine basic block.
489 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
490 MachineBasicBlock *MBB);
492 } // end namespace llvm