blob: 18e15af4577f171fe66aa1b3550b7ef6d8734685 [file] [log] [blame]
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001//===-- SelectionDAGBuild.h - Selection-DAG building ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements routines for translating from LLVM IR into SelectionDAG IR.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef SELECTIONDAGBUILD_H
15#define SELECTIONDAGBUILD_H
16
17#include "llvm/Constants.h"
18#include "llvm/ADT/APInt.h"
19#include "llvm/ADT/DenseMap.h"
20#ifndef NDEBUG
21#include "llvm/ADT/SmallSet.h"
22#endif
23#include "llvm/CodeGen/ValueTypes.h"
24#include "llvm/CodeGen/SelectionDAGNodes.h"
25#include "llvm/Support/CallSite.h"
26#include <vector>
27#include <set>
28
29namespace llvm {
30
31class AliasAnalysis;
32class AllocaInst;
33class BasicBlock;
34class BitCastInst;
35class BranchInst;
36class CallInst;
37class ExtractElementInst;
38class ExtractValueInst;
39class FCmpInst;
40class FPExtInst;
41class FPToSIInst;
42class FPToUIInst;
43class FPTruncInst;
44class FreeInst;
45class Function;
46class GetElementPtrInst;
47class GCFunctionInfo;
48class ICmpInst;
49class IntToPtrInst;
50class InvokeInst;
51class InsertElementInst;
52class InsertValueInst;
53class Instruction;
54class LoadInst;
55class MachineBasicBlock;
56class MachineFunction;
57class MachineInstr;
58class MachineModuleInfo;
59class MachineRegisterInfo;
60class MallocInst;
61class PHINode;
62class PtrToIntInst;
63class ReturnInst;
64class SDISelAsmOperandInfo;
65class SExtInst;
66class SelectInst;
67class ShuffleVectorInst;
68class SIToFPInst;
69class StoreInst;
70class SwitchInst;
71class TargetData;
72class TargetLowering;
73class TruncInst;
74class UIToFPInst;
75class UnreachableInst;
76class UnwindInst;
77class VICmpInst;
78class VFCmpInst;
79class VAArgInst;
80class ZExtInst;
81
82//===--------------------------------------------------------------------===//
83/// FunctionLoweringInfo - This contains information that is global to a
84/// function that is used when lowering a region of the function.
85///
86class FunctionLoweringInfo {
87public:
88 TargetLowering &TLI;
89 Function *Fn;
90 MachineFunction *MF;
91 MachineRegisterInfo *RegInfo;
92
93 explicit FunctionLoweringInfo(TargetLowering &TLI);
94
95 /// set - Initialize this FunctionLoweringInfo with the given Function
96 /// and its associated MachineFunction.
97 ///
98 void set(Function &Fn, MachineFunction &MF, bool EnableFastISel);
99
100 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
101 DenseMap<const BasicBlock*, MachineBasicBlock *> MBBMap;
102
103 /// ValueMap - Since we emit code for the function a basic block at a time,
104 /// we must remember which virtual registers hold the values for
105 /// cross-basic-block values.
106 DenseMap<const Value*, unsigned> ValueMap;
107
108 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
109 /// the entry block. This allows the allocas to be efficiently referenced
110 /// anywhere in the function.
111 DenseMap<const AllocaInst*, int> StaticAllocaMap;
112
113#ifndef NDEBUG
114 SmallSet<Instruction*, 8> CatchInfoLost;
115 SmallSet<Instruction*, 8> CatchInfoFound;
116#endif
117
118 unsigned MakeReg(MVT VT);
119
120 /// isExportedInst - Return true if the specified value is an instruction
121 /// exported from its block.
122 bool isExportedInst(const Value *V) {
123 return ValueMap.count(V);
124 }
125
126 unsigned CreateRegForValue(const Value *V);
127
128 unsigned InitializeRegForValue(const Value *V) {
129 unsigned &R = ValueMap[V];
130 assert(R == 0 && "Already initialized this value register!");
131 return R = CreateRegForValue(V);
132 }
133
134 struct LiveOutInfo {
135 unsigned NumSignBits;
136 APInt KnownOne, KnownZero;
137 LiveOutInfo() : NumSignBits(0) {}
138 };
139
140 /// LiveOutRegInfo - Information about live out vregs, indexed by their
141 /// register number offset by 'FirstVirtualRegister'.
142 std::vector<LiveOutInfo> LiveOutRegInfo;
143
144 /// clear - Clear out all the function-specific state. This returns this
145 /// FunctionLoweringInfo to an empty state, ready to be used for a
146 /// different function.
147 void clear() {
148 MBBMap.clear();
149 ValueMap.clear();
150 StaticAllocaMap.clear();
151#ifndef NDEBUG
152 CatchInfoLost.clear();
153 CatchInfoFound.clear();
154#endif
155 LiveOutRegInfo.clear();
156 }
157};
158
159//===----------------------------------------------------------------------===//
160/// SelectionDAGLowering - This is the common target-independent lowering
161/// implementation that is parameterized by a TargetLowering object.
162/// Also, targets can overload any lowering method.
163///
164class SelectionDAGLowering {
165 MachineBasicBlock *CurMBB;
166
167 DenseMap<const Value*, SDValue> NodeMap;
168
169 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
170 /// them up and then emit token factor nodes when possible. This allows us to
171 /// get simple disambiguation between loads without worrying about alias
172 /// analysis.
173 SmallVector<SDValue, 8> PendingLoads;
174
175 /// PendingExports - CopyToReg nodes that copy values to virtual registers
176 /// for export to other blocks need to be emitted before any terminator
177 /// instruction, but they have no other ordering requirements. We bunch them
178 /// up and the emit a single tokenfactor for them just before terminator
179 /// instructions.
180 SmallVector<SDValue, 8> PendingExports;
181
182 /// Case - A struct to record the Value for a switch case, and the
183 /// case's target basic block.
184 struct Case {
185 Constant* Low;
186 Constant* High;
187 MachineBasicBlock* BB;
188
189 Case() : Low(0), High(0), BB(0) { }
190 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
191 Low(low), High(high), BB(bb) { }
192 uint64_t size() const {
193 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
194 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
195 return (rHigh - rLow + 1ULL);
196 }
197 };
198
199 struct CaseBits {
200 uint64_t Mask;
201 MachineBasicBlock* BB;
202 unsigned Bits;
203
204 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
205 Mask(mask), BB(bb), Bits(bits) { }
206 };
207
208 typedef std::vector<Case> CaseVector;
209 typedef std::vector<CaseBits> CaseBitsVector;
210 typedef CaseVector::iterator CaseItr;
211 typedef std::pair<CaseItr, CaseItr> CaseRange;
212
213 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
214 /// of conditional branches.
215 struct CaseRec {
216 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
217 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
218
219 /// CaseBB - The MBB in which to emit the compare and branch
220 MachineBasicBlock *CaseBB;
221 /// LT, GE - If nonzero, we know the current case value must be less-than or
222 /// greater-than-or-equal-to these Constants.
223 Constant *LT;
224 Constant *GE;
225 /// Range - A pair of iterators representing the range of case values to be
226 /// processed at this point in the binary search tree.
227 CaseRange Range;
228 };
229
230 typedef std::vector<CaseRec> CaseRecVector;
231
232 /// The comparison function for sorting the switch case values in the vector.
233 /// WARNING: Case ranges should be disjoint!
234 struct CaseCmp {
235 bool operator () (const Case& C1, const Case& C2) {
236 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
237 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
238 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
239 return CI1->getValue().slt(CI2->getValue());
240 }
241 };
242
243 struct CaseBitsCmp {
244 bool operator () (const CaseBits& C1, const CaseBits& C2) {
245 return C1.Bits > C2.Bits;
246 }
247 };
248
249 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
250
251 /// CaseBlock - This structure is used to communicate between SDLowering and
252 /// SDISel for the code generation of additional basic blocks needed by multi-
253 /// case switch statements.
254 struct CaseBlock {
255 CaseBlock(ISD::CondCode cc, Value *cmplhs, Value *cmprhs, Value *cmpmiddle,
256 MachineBasicBlock *truebb, MachineBasicBlock *falsebb,
257 MachineBasicBlock *me)
258 : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
259 TrueBB(truebb), FalseBB(falsebb), ThisBB(me) {}
260 // CC - the condition code to use for the case block's setcc node
261 ISD::CondCode CC;
262 // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
263 // Emit by default LHS op RHS. MHS is used for range comparisons:
264 // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
265 Value *CmpLHS, *CmpMHS, *CmpRHS;
266 // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
267 MachineBasicBlock *TrueBB, *FalseBB;
268 // ThisBB - the block into which to emit the code for the setcc and branches
269 MachineBasicBlock *ThisBB;
270 };
271 struct JumpTable {
272 JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
273 MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
274
275 /// Reg - the virtual register containing the index of the jump table entry
276 //. to jump to.
277 unsigned Reg;
278 /// JTI - the JumpTableIndex for this jump table in the function.
279 unsigned JTI;
280 /// MBB - the MBB into which to emit the code for the indirect jump.
281 MachineBasicBlock *MBB;
282 /// Default - the MBB of the default bb, which is a successor of the range
283 /// check MBB. This is when updating PHI nodes in successors.
284 MachineBasicBlock *Default;
285 };
286 struct JumpTableHeader {
287 JumpTableHeader(uint64_t F, uint64_t L, Value* SV, MachineBasicBlock* H,
288 bool E = false):
289 First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
290 uint64_t First;
291 uint64_t Last;
292 Value *SValue;
293 MachineBasicBlock *HeaderBB;
294 bool Emitted;
295 };
296 typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
297
298 struct BitTestCase {
299 BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr):
300 Mask(M), ThisBB(T), TargetBB(Tr) { }
301 uint64_t Mask;
302 MachineBasicBlock* ThisBB;
303 MachineBasicBlock* TargetBB;
304 };
305
306 typedef SmallVector<BitTestCase, 3> BitTestInfo;
307
308 struct BitTestBlock {
309 BitTestBlock(uint64_t F, uint64_t R, Value* SV,
310 unsigned Rg, bool E,
311 MachineBasicBlock* P, MachineBasicBlock* D,
312 const BitTestInfo& C):
313 First(F), Range(R), SValue(SV), Reg(Rg), Emitted(E),
314 Parent(P), Default(D), Cases(C) { }
315 uint64_t First;
316 uint64_t Range;
317 Value *SValue;
318 unsigned Reg;
319 bool Emitted;
320 MachineBasicBlock *Parent;
321 MachineBasicBlock *Default;
322 BitTestInfo Cases;
323 };
324
325public:
326 // TLI - This is information that describes the available target features we
327 // need for lowering. This indicates when operations are unavailable,
328 // implemented with a libcall, etc.
329 TargetLowering &TLI;
330 SelectionDAG &DAG;
331 const TargetData *TD;
332 AliasAnalysis *AA;
333
334 /// SwitchCases - Vector of CaseBlock structures used to communicate
335 /// SwitchInst code generation information.
336 std::vector<CaseBlock> SwitchCases;
337 /// JTCases - Vector of JumpTable structures used to communicate
338 /// SwitchInst code generation information.
339 std::vector<JumpTableBlock> JTCases;
340 /// BitTestCases - Vector of BitTestBlock structures used to communicate
341 /// SwitchInst code generation information.
342 std::vector<BitTestBlock> BitTestCases;
343
344 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
345
346 // Emit PHI-node-operand constants only once even if used by multiple
347 // PHI nodes.
348 DenseMap<Constant*, unsigned> ConstantsOut;
349
350 /// FuncInfo - Information about the function as a whole.
351 ///
352 FunctionLoweringInfo &FuncInfo;
353
354 /// GFI - Garbage collection metadata for the function.
355 GCFunctionInfo *GFI;
356
357 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
358 FunctionLoweringInfo &funcinfo)
359 : TLI(tli), DAG(dag), FuncInfo(funcinfo) {
360 }
361
362 void init(GCFunctionInfo *gfi, AliasAnalysis &aa);
363
364 /// clear - Clear out the curret SelectionDAG and the associated
365 /// state and prepare this SelectionDAGLowering object to be used
366 /// for a new block. This doesn't clear out information about
367 /// additional blocks that are needed to complete switch lowering
368 /// or PHI node updating; that information is cleared out as it is
369 /// consumed.
370 void clear();
371
372 /// getRoot - Return the current virtual root of the Selection DAG,
373 /// flushing any PendingLoad items. This must be done before emitting
374 /// a store or any other node that may need to be ordered after any
375 /// prior load instructions.
376 ///
377 SDValue getRoot();
378
379 /// getControlRoot - Similar to getRoot, but instead of flushing all the
380 /// PendingLoad items, flush all the PendingExports items. It is necessary
381 /// to do this before emitting a terminator instruction.
382 ///
383 SDValue getControlRoot();
384
385 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
386
387 void visit(Instruction &I);
388
389 void visit(unsigned Opcode, User &I);
390
391 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
392
393 SDValue getValue(const Value *V);
394
395 void setValue(const Value *V, SDValue NewN) {
396 SDValue &N = NodeMap[V];
397 assert(N.getNode() == 0 && "Already set a value for this node!");
398 N = NewN;
399 }
400
401 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
402 std::set<unsigned> &OutputRegs,
403 std::set<unsigned> &InputRegs);
404
405 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
406 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
407 unsigned Opc);
408 bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases);
409 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
410 void ExportFromCurrentBlock(Value *V);
411 void LowerCallTo(CallSite CS, SDValue Callee, bool IsTailCall,
412 MachineBasicBlock *LandingPad = NULL);
413
414private:
415 // Terminator instructions.
416 void visitRet(ReturnInst &I);
417 void visitBr(BranchInst &I);
418 void visitSwitch(SwitchInst &I);
419 void visitUnreachable(UnreachableInst &I) { /* noop */ }
420
421 // Helpers for visitSwitch
422 bool handleSmallSwitchRange(CaseRec& CR,
423 CaseRecVector& WorkList,
424 Value* SV,
425 MachineBasicBlock* Default);
426 bool handleJTSwitchCase(CaseRec& CR,
427 CaseRecVector& WorkList,
428 Value* SV,
429 MachineBasicBlock* Default);
430 bool handleBTSplitSwitchCase(CaseRec& CR,
431 CaseRecVector& WorkList,
432 Value* SV,
433 MachineBasicBlock* Default);
434 bool handleBitTestsSwitchCase(CaseRec& CR,
435 CaseRecVector& WorkList,
436 Value* SV,
437 MachineBasicBlock* Default);
438public:
439 void visitSwitchCase(CaseBlock &CB);
440 void visitBitTestHeader(BitTestBlock &B);
441 void visitBitTestCase(MachineBasicBlock* NextMBB,
442 unsigned Reg,
443 BitTestCase &B);
444 void visitJumpTable(JumpTable &JT);
445 void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH);
446
447private:
448 // These all get lowered before this pass.
449 void visitInvoke(InvokeInst &I);
450 void visitUnwind(UnwindInst &I);
451
452 void visitBinary(User &I, unsigned OpCode);
453 void visitShift(User &I, unsigned Opcode);
454 void visitAdd(User &I);
455 void visitSub(User &I);
456 void visitMul(User &I);
457 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
458 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
459 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
460 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
461 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
462 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
463 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
464 void visitOr (User &I) { visitBinary(I, ISD::OR); }
465 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
466 void visitShl (User &I) { visitShift(I, ISD::SHL); }
467 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
468 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
469 void visitICmp(User &I);
470 void visitFCmp(User &I);
471 void visitVICmp(User &I);
472 void visitVFCmp(User &I);
473 // Visit the conversion instructions
474 void visitTrunc(User &I);
475 void visitZExt(User &I);
476 void visitSExt(User &I);
477 void visitFPTrunc(User &I);
478 void visitFPExt(User &I);
479 void visitFPToUI(User &I);
480 void visitFPToSI(User &I);
481 void visitUIToFP(User &I);
482 void visitSIToFP(User &I);
483 void visitPtrToInt(User &I);
484 void visitIntToPtr(User &I);
485 void visitBitCast(User &I);
486
487 void visitExtractElement(User &I);
488 void visitInsertElement(User &I);
489 void visitShuffleVector(User &I);
490
491 void visitExtractValue(ExtractValueInst &I);
492 void visitInsertValue(InsertValueInst &I);
493
494 void visitGetElementPtr(User &I);
495 void visitSelect(User &I);
496
497 void visitMalloc(MallocInst &I);
498 void visitFree(FreeInst &I);
499 void visitAlloca(AllocaInst &I);
500 void visitLoad(LoadInst &I);
501 void visitStore(StoreInst &I);
502 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
503 void visitCall(CallInst &I);
504 void visitInlineAsm(CallSite CS);
505 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
506 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
507
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +0000508 void visitPow(CallInst &I);
Dale Johannesen601d3c02008-09-05 01:48:15 +0000509 void visitExp2(CallInst &I);
Dale Johannesen59e577f2008-09-05 18:38:42 +0000510 void visitExp(CallInst &I);
511 void visitLog(CallInst &I);
512 void visitLog2(CallInst &I);
513 void visitLog10(CallInst &I);
Dale Johannesen601d3c02008-09-05 01:48:15 +0000514
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000515 void visitVAStart(CallInst &I);
516 void visitVAArg(VAArgInst &I);
517 void visitVAEnd(CallInst &I);
518 void visitVACopy(CallInst &I);
519
520 void visitUserOp1(Instruction &I) {
521 assert(0 && "UserOp1 should not exist at instruction selection time!");
522 abort();
523 }
524 void visitUserOp2(Instruction &I) {
525 assert(0 && "UserOp2 should not exist at instruction selection time!");
526 abort();
527 }
528
529 const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
530};
531
532/// AddCatchInfo - Extract the personality and type infos from an eh.selector
533/// call, and add them to the specified machine basic block.
534void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
535 MachineBasicBlock *MBB);
536
537} // end namespace llvm
538
539#endif