blob: 92e34bbc48f88cd96d92a0c5f2a4397a754f3bbb [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/ADT/BitVector.h"
16#include "llvm/Analysis/AliasAnalysis.h"
17#include "llvm/CodeGen/SelectionDAGISel.h"
18#include "llvm/CodeGen/ScheduleDAG.h"
19#include "llvm/Constants.h"
20#include "llvm/CallingConv.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
23#include "llvm/GlobalVariable.h"
24#include "llvm/InlineAsm.h"
25#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
27#include "llvm/IntrinsicInst.h"
28#include "llvm/ParameterAttributes.h"
29#include "llvm/CodeGen/MachineModuleInfo.h"
30#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
32#include "llvm/CodeGen/MachineJumpTableInfo.h"
33#include "llvm/CodeGen/MachineInstrBuilder.h"
34#include "llvm/CodeGen/SchedulerRegistry.h"
35#include "llvm/CodeGen/SelectionDAG.h"
36#include "llvm/CodeGen/SSARegMap.h"
37#include "llvm/Target/MRegisterInfo.h"
38#include "llvm/Target/TargetData.h"
39#include "llvm/Target/TargetFrameInfo.h"
40#include "llvm/Target/TargetInstrInfo.h"
41#include "llvm/Target/TargetLowering.h"
42#include "llvm/Target/TargetMachine.h"
43#include "llvm/Target/TargetOptions.h"
44#include "llvm/Support/MathExtras.h"
45#include "llvm/Support/Debug.h"
46#include "llvm/Support/Compiler.h"
47#include <algorithm>
48using namespace llvm;
49
50#ifndef NDEBUG
51static cl::opt<bool>
52ViewISelDAGs("view-isel-dags", cl::Hidden,
53 cl::desc("Pop up a window to show isel dags as they are selected"));
54static cl::opt<bool>
55ViewSchedDAGs("view-sched-dags", cl::Hidden,
56 cl::desc("Pop up a window to show sched dags as they are processed"));
57#else
58static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
59#endif
60
61//===---------------------------------------------------------------------===//
62///
63/// RegisterScheduler class - Track the registration of instruction schedulers.
64///
65//===---------------------------------------------------------------------===//
66MachinePassRegistry RegisterScheduler::Registry;
67
68//===---------------------------------------------------------------------===//
69///
70/// ISHeuristic command line option for instruction schedulers.
71///
72//===---------------------------------------------------------------------===//
73namespace {
74 cl::opt<RegisterScheduler::FunctionPassCtor, false,
75 RegisterPassParser<RegisterScheduler> >
76 ISHeuristic("pre-RA-sched",
77 cl::init(&createDefaultScheduler),
78 cl::desc("Instruction schedulers available (before register allocation):"));
79
80 static RegisterScheduler
81 defaultListDAGScheduler("default", " Best scheduler for the target",
82 createDefaultScheduler);
83} // namespace
84
85namespace { struct AsmOperandInfo; }
86
87namespace {
88 /// RegsForValue - This struct represents the physical registers that a
89 /// particular value is assigned and the type information about the value.
90 /// This is needed because values can be promoted into larger registers and
91 /// expanded into multiple smaller registers than the value.
92 struct VISIBILITY_HIDDEN RegsForValue {
93 /// Regs - This list holds the register (for legal and promoted values)
94 /// or register set (for expanded values) that the value should be assigned
95 /// to.
96 std::vector<unsigned> Regs;
97
98 /// RegVT - The value type of each register.
99 ///
100 MVT::ValueType RegVT;
101
102 /// ValueVT - The value type of the LLVM value, which may be promoted from
103 /// RegVT or made from merging the two expanded parts.
104 MVT::ValueType ValueVT;
105
106 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
107
108 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
109 : RegVT(regvt), ValueVT(valuevt) {
110 Regs.push_back(Reg);
111 }
112 RegsForValue(const std::vector<unsigned> &regs,
113 MVT::ValueType regvt, MVT::ValueType valuevt)
114 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
115 }
116
117 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
118 /// this value and returns the result as a ValueVT value. This uses
119 /// Chain/Flag as the input and updates them for the output Chain/Flag.
120 /// If the Flag pointer is NULL, no flag is used.
121 SDOperand getCopyFromRegs(SelectionDAG &DAG,
122 SDOperand &Chain, SDOperand *Flag) const;
123
124 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
125 /// specified value into the registers specified by this object. This uses
126 /// Chain/Flag as the input and updates them for the output Chain/Flag.
127 /// If the Flag pointer is NULL, no flag is used.
128 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
129 SDOperand &Chain, SDOperand *Flag) const;
130
131 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
132 /// operand list. This adds the code marker and includes the number of
133 /// values added into it.
134 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
135 std::vector<SDOperand> &Ops) const;
136 };
137}
138
139namespace llvm {
140 //===--------------------------------------------------------------------===//
141 /// createDefaultScheduler - This creates an instruction scheduler appropriate
142 /// for the target.
143 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
144 SelectionDAG *DAG,
145 MachineBasicBlock *BB) {
146 TargetLowering &TLI = IS->getTargetLowering();
147
148 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
149 return createTDListDAGScheduler(IS, DAG, BB);
150 } else {
151 assert(TLI.getSchedulingPreference() ==
152 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
153 return createBURRListDAGScheduler(IS, DAG, BB);
154 }
155 }
156
157
158 //===--------------------------------------------------------------------===//
159 /// FunctionLoweringInfo - This contains information that is global to a
160 /// function that is used when lowering a region of the function.
161 class FunctionLoweringInfo {
162 public:
163 TargetLowering &TLI;
164 Function &Fn;
165 MachineFunction &MF;
166 SSARegMap *RegMap;
167
168 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
169
170 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
171 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
172
173 /// ValueMap - Since we emit code for the function a basic block at a time,
174 /// we must remember which virtual registers hold the values for
175 /// cross-basic-block values.
176 DenseMap<const Value*, unsigned> ValueMap;
177
178 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
179 /// the entry block. This allows the allocas to be efficiently referenced
180 /// anywhere in the function.
181 std::map<const AllocaInst*, int> StaticAllocaMap;
182
183#ifndef NDEBUG
184 SmallSet<Instruction*, 8> CatchInfoLost;
185 SmallSet<Instruction*, 8> CatchInfoFound;
186#endif
187
188 unsigned MakeReg(MVT::ValueType VT) {
189 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
190 }
191
192 /// isExportedInst - Return true if the specified value is an instruction
193 /// exported from its block.
194 bool isExportedInst(const Value *V) {
195 return ValueMap.count(V);
196 }
197
198 unsigned CreateRegForValue(const Value *V);
199
200 unsigned InitializeRegForValue(const Value *V) {
201 unsigned &R = ValueMap[V];
202 assert(R == 0 && "Already initialized this value register!");
203 return R = CreateRegForValue(V);
204 }
205 };
206}
207
208/// isSelector - Return true if this instruction is a call to the
209/// eh.selector intrinsic.
210static bool isSelector(Instruction *I) {
211 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
212 return II->getIntrinsicID() == Intrinsic::eh_selector;
213 return false;
214}
215
216/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
217/// PHI nodes or outside of the basic block that defines it, or used by a
218/// switch instruction, which may expand to multiple basic blocks.
219static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
220 if (isa<PHINode>(I)) return true;
221 BasicBlock *BB = I->getParent();
222 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
223 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
224 // FIXME: Remove switchinst special case.
225 isa<SwitchInst>(*UI))
226 return true;
227 return false;
228}
229
230/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
231/// entry block, return true. This includes arguments used by switches, since
232/// the switch may expand into multiple basic blocks.
233static bool isOnlyUsedInEntryBlock(Argument *A) {
234 BasicBlock *Entry = A->getParent()->begin();
235 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
236 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
237 return false; // Use not in entry block.
238 return true;
239}
240
241FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
242 Function &fn, MachineFunction &mf)
243 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
244
245 // Create a vreg for each argument register that is not dead and is used
246 // outside of the entry block for the function.
247 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
248 AI != E; ++AI)
249 if (!isOnlyUsedInEntryBlock(AI))
250 InitializeRegForValue(AI);
251
252 // Initialize the mapping of values to registers. This is only set up for
253 // instruction values that are used outside of the block that defines
254 // them.
255 Function::iterator BB = Fn.begin(), EB = Fn.end();
256 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
257 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
258 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
259 const Type *Ty = AI->getAllocatedType();
260 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
261 unsigned Align =
262 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
263 AI->getAlignment());
264
265 TySize *= CUI->getZExtValue(); // Get total allocated size.
266 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
267 StaticAllocaMap[AI] =
268 MF.getFrameInfo()->CreateStackObject(TySize, Align);
269 }
270
271 for (; BB != EB; ++BB)
272 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
273 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
274 if (!isa<AllocaInst>(I) ||
275 !StaticAllocaMap.count(cast<AllocaInst>(I)))
276 InitializeRegForValue(I);
277
278 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
279 // also creates the initial PHI MachineInstrs, though none of the input
280 // operands are populated.
281 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
282 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
283 MBBMap[BB] = MBB;
284 MF.getBasicBlockList().push_back(MBB);
285
286 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
287 // appropriate.
288 PHINode *PN;
289 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
290 if (PN->use_empty()) continue;
291
292 MVT::ValueType VT = TLI.getValueType(PN->getType());
293 unsigned NumRegisters = TLI.getNumRegisters(VT);
294 unsigned PHIReg = ValueMap[PN];
295 assert(PHIReg && "PHI node does not have an assigned virtual register!");
296 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
297 for (unsigned i = 0; i != NumRegisters; ++i)
298 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
299 }
300 }
301}
302
303/// CreateRegForValue - Allocate the appropriate number of virtual registers of
304/// the correctly promoted or expanded types. Assign these registers
305/// consecutive vreg numbers and return the first assigned number.
306unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
307 MVT::ValueType VT = TLI.getValueType(V->getType());
308
309 unsigned NumRegisters = TLI.getNumRegisters(VT);
310 MVT::ValueType RegisterVT = TLI.getRegisterType(VT);
311
312 unsigned R = MakeReg(RegisterVT);
313 for (unsigned i = 1; i != NumRegisters; ++i)
314 MakeReg(RegisterVT);
315
316 return R;
317}
318
319//===----------------------------------------------------------------------===//
320/// SelectionDAGLowering - This is the common target-independent lowering
321/// implementation that is parameterized by a TargetLowering object.
322/// Also, targets can overload any lowering method.
323///
324namespace llvm {
325class SelectionDAGLowering {
326 MachineBasicBlock *CurMBB;
327
328 DenseMap<const Value*, SDOperand> NodeMap;
329
330 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
331 /// them up and then emit token factor nodes when possible. This allows us to
332 /// get simple disambiguation between loads without worrying about alias
333 /// analysis.
334 std::vector<SDOperand> PendingLoads;
335
336 /// Case - A struct to record the Value for a switch case, and the
337 /// case's target basic block.
338 struct Case {
339 Constant* Low;
340 Constant* High;
341 MachineBasicBlock* BB;
342
343 Case() : Low(0), High(0), BB(0) { }
344 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
345 Low(low), High(high), BB(bb) { }
346 uint64_t size() const {
347 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
348 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
349 return (rHigh - rLow + 1ULL);
350 }
351 };
352
353 struct CaseBits {
354 uint64_t Mask;
355 MachineBasicBlock* BB;
356 unsigned Bits;
357
358 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
359 Mask(mask), BB(bb), Bits(bits) { }
360 };
361
362 typedef std::vector<Case> CaseVector;
363 typedef std::vector<CaseBits> CaseBitsVector;
364 typedef CaseVector::iterator CaseItr;
365 typedef std::pair<CaseItr, CaseItr> CaseRange;
366
367 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
368 /// of conditional branches.
369 struct CaseRec {
370 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
371 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
372
373 /// CaseBB - The MBB in which to emit the compare and branch
374 MachineBasicBlock *CaseBB;
375 /// LT, GE - If nonzero, we know the current case value must be less-than or
376 /// greater-than-or-equal-to these Constants.
377 Constant *LT;
378 Constant *GE;
379 /// Range - A pair of iterators representing the range of case values to be
380 /// processed at this point in the binary search tree.
381 CaseRange Range;
382 };
383
384 typedef std::vector<CaseRec> CaseRecVector;
385
386 /// The comparison function for sorting the switch case values in the vector.
387 /// WARNING: Case ranges should be disjoint!
388 struct CaseCmp {
389 bool operator () (const Case& C1, const Case& C2) {
390 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
391 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
392 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
393 return CI1->getValue().slt(CI2->getValue());
394 }
395 };
396
397 struct CaseBitsCmp {
398 bool operator () (const CaseBits& C1, const CaseBits& C2) {
399 return C1.Bits > C2.Bits;
400 }
401 };
402
403 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
404
405public:
406 // TLI - This is information that describes the available target features we
407 // need for lowering. This indicates when operations are unavailable,
408 // implemented with a libcall, etc.
409 TargetLowering &TLI;
410 SelectionDAG &DAG;
411 const TargetData *TD;
Dan Gohmancc863aa2007-08-27 16:26:13 +0000412 AliasAnalysis &AA;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000413
414 /// SwitchCases - Vector of CaseBlock structures used to communicate
415 /// SwitchInst code generation information.
416 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
417 /// JTCases - Vector of JumpTable structures used to communicate
418 /// SwitchInst code generation information.
419 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
420 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
421
422 /// FuncInfo - Information about the function as a whole.
423 ///
424 FunctionLoweringInfo &FuncInfo;
425
426 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohmancc863aa2007-08-27 16:26:13 +0000427 AliasAnalysis &aa,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000428 FunctionLoweringInfo &funcinfo)
Dan Gohmancc863aa2007-08-27 16:26:13 +0000429 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430 FuncInfo(funcinfo) {
431 }
432
433 /// getRoot - Return the current virtual root of the Selection DAG.
434 ///
435 SDOperand getRoot() {
436 if (PendingLoads.empty())
437 return DAG.getRoot();
438
439 if (PendingLoads.size() == 1) {
440 SDOperand Root = PendingLoads[0];
441 DAG.setRoot(Root);
442 PendingLoads.clear();
443 return Root;
444 }
445
446 // Otherwise, we have to make a token factor node.
447 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
448 &PendingLoads[0], PendingLoads.size());
449 PendingLoads.clear();
450 DAG.setRoot(Root);
451 return Root;
452 }
453
454 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
455
456 void visit(Instruction &I) { visit(I.getOpcode(), I); }
457
458 void visit(unsigned Opcode, User &I) {
459 // Note: this doesn't use InstVisitor, because it has to work with
460 // ConstantExpr's in addition to instructions.
461 switch (Opcode) {
462 default: assert(0 && "Unknown instruction type encountered!");
463 abort();
464 // Build the switch statement using the Instruction.def file.
465#define HANDLE_INST(NUM, OPCODE, CLASS) \
466 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
467#include "llvm/Instruction.def"
468 }
469 }
470
471 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
472
473 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
474 const Value *SV, SDOperand Root,
475 bool isVolatile, unsigned Alignment);
476
477 SDOperand getIntPtrConstant(uint64_t Val) {
478 return DAG.getConstant(Val, TLI.getPointerTy());
479 }
480
481 SDOperand getValue(const Value *V);
482
483 void setValue(const Value *V, SDOperand NewN) {
484 SDOperand &N = NodeMap[V];
485 assert(N.Val == 0 && "Already set a value for this node!");
486 N = NewN;
487 }
488
489 void GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
490 std::set<unsigned> &OutputRegs,
491 std::set<unsigned> &InputRegs);
492
493 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
494 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
495 unsigned Opc);
496 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
497 void ExportFromCurrentBlock(Value *V);
498 void LowerCallTo(Instruction &I,
499 const Type *CalledValueTy, unsigned CallingConv,
500 bool IsTailCall, SDOperand Callee, unsigned OpIdx,
501 MachineBasicBlock *LandingPad = NULL);
502
503 // Terminator instructions.
504 void visitRet(ReturnInst &I);
505 void visitBr(BranchInst &I);
506 void visitSwitch(SwitchInst &I);
507 void visitUnreachable(UnreachableInst &I) { /* noop */ }
508
509 // Helpers for visitSwitch
510 bool handleSmallSwitchRange(CaseRec& CR,
511 CaseRecVector& WorkList,
512 Value* SV,
513 MachineBasicBlock* Default);
514 bool handleJTSwitchCase(CaseRec& CR,
515 CaseRecVector& WorkList,
516 Value* SV,
517 MachineBasicBlock* Default);
518 bool handleBTSplitSwitchCase(CaseRec& CR,
519 CaseRecVector& WorkList,
520 Value* SV,
521 MachineBasicBlock* Default);
522 bool handleBitTestsSwitchCase(CaseRec& CR,
523 CaseRecVector& WorkList,
524 Value* SV,
525 MachineBasicBlock* Default);
526 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
527 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
528 void visitBitTestCase(MachineBasicBlock* NextMBB,
529 unsigned Reg,
530 SelectionDAGISel::BitTestCase &B);
531 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
532 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
533 SelectionDAGISel::JumpTableHeader &JTH);
534
535 // These all get lowered before this pass.
536 void visitInvoke(InvokeInst &I);
537 void visitUnwind(UnwindInst &I);
538
539 void visitBinary(User &I, unsigned OpCode);
540 void visitShift(User &I, unsigned Opcode);
541 void visitAdd(User &I) {
542 if (I.getType()->isFPOrFPVector())
543 visitBinary(I, ISD::FADD);
544 else
545 visitBinary(I, ISD::ADD);
546 }
547 void visitSub(User &I);
548 void visitMul(User &I) {
549 if (I.getType()->isFPOrFPVector())
550 visitBinary(I, ISD::FMUL);
551 else
552 visitBinary(I, ISD::MUL);
553 }
554 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
555 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
556 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
557 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
558 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
559 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
560 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
561 void visitOr (User &I) { visitBinary(I, ISD::OR); }
562 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
563 void visitShl (User &I) { visitShift(I, ISD::SHL); }
564 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
565 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
566 void visitICmp(User &I);
567 void visitFCmp(User &I);
568 // Visit the conversion instructions
569 void visitTrunc(User &I);
570 void visitZExt(User &I);
571 void visitSExt(User &I);
572 void visitFPTrunc(User &I);
573 void visitFPExt(User &I);
574 void visitFPToUI(User &I);
575 void visitFPToSI(User &I);
576 void visitUIToFP(User &I);
577 void visitSIToFP(User &I);
578 void visitPtrToInt(User &I);
579 void visitIntToPtr(User &I);
580 void visitBitCast(User &I);
581
582 void visitExtractElement(User &I);
583 void visitInsertElement(User &I);
584 void visitShuffleVector(User &I);
585
586 void visitGetElementPtr(User &I);
587 void visitSelect(User &I);
588
589 void visitMalloc(MallocInst &I);
590 void visitFree(FreeInst &I);
591 void visitAlloca(AllocaInst &I);
592 void visitLoad(LoadInst &I);
593 void visitStore(StoreInst &I);
594 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
595 void visitCall(CallInst &I);
596 void visitInlineAsm(CallInst &I);
597 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
598 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
599
600 void visitVAStart(CallInst &I);
601 void visitVAArg(VAArgInst &I);
602 void visitVAEnd(CallInst &I);
603 void visitVACopy(CallInst &I);
604
605 void visitMemIntrinsic(CallInst &I, unsigned Op);
606
607 void visitUserOp1(Instruction &I) {
608 assert(0 && "UserOp1 should not exist at instruction selection time!");
609 abort();
610 }
611 void visitUserOp2(Instruction &I) {
612 assert(0 && "UserOp2 should not exist at instruction selection time!");
613 abort();
614 }
615};
616} // end namespace llvm
617
618
619/// getCopyFromParts - Create a value that contains the
620/// specified legal parts combined into the value they represent.
621static SDOperand getCopyFromParts(SelectionDAG &DAG,
622 const SDOperand *Parts,
623 unsigned NumParts,
624 MVT::ValueType PartVT,
625 MVT::ValueType ValueVT,
626 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
627 if (!MVT::isVector(ValueVT) || NumParts == 1) {
628 SDOperand Val = Parts[0];
629
630 // If the value was expanded, copy from the top part.
631 if (NumParts > 1) {
632 assert(NumParts == 2 &&
633 "Cannot expand to more than 2 elts yet!");
634 SDOperand Hi = Parts[1];
635 if (!DAG.getTargetLoweringInfo().isLittleEndian())
636 std::swap(Val, Hi);
637 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
638 }
639
640 // Otherwise, if the value was promoted or extended, truncate it to the
641 // appropriate type.
642 if (PartVT == ValueVT)
643 return Val;
644
645 if (MVT::isVector(PartVT)) {
646 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
647 return DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
648 }
649
650 if (MVT::isInteger(PartVT) &&
651 MVT::isInteger(ValueVT)) {
652 if (ValueVT < PartVT) {
653 // For a truncate, see if we have any information to
654 // indicate whether the truncated bits will always be
655 // zero or sign-extension.
656 if (AssertOp != ISD::DELETED_NODE)
657 Val = DAG.getNode(AssertOp, PartVT, Val,
658 DAG.getValueType(ValueVT));
659 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
660 } else {
661 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
662 }
663 }
664
665 if (MVT::isFloatingPoint(PartVT) &&
666 MVT::isFloatingPoint(ValueVT))
667 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
668
669 if (MVT::getSizeInBits(PartVT) ==
670 MVT::getSizeInBits(ValueVT))
671 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
672
673 assert(0 && "Unknown mismatch!");
674 }
675
676 // Handle a multi-element vector.
677 MVT::ValueType IntermediateVT, RegisterVT;
678 unsigned NumIntermediates;
679 unsigned NumRegs =
680 DAG.getTargetLoweringInfo()
681 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
682 RegisterVT);
683
684 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
685 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
686 assert(RegisterVT == Parts[0].getValueType() &&
687 "Part type doesn't match part!");
688
689 // Assemble the parts into intermediate operands.
690 SmallVector<SDOperand, 8> Ops(NumIntermediates);
691 if (NumIntermediates == NumParts) {
692 // If the register was not expanded, truncate or copy the value,
693 // as appropriate.
694 for (unsigned i = 0; i != NumParts; ++i)
695 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
696 PartVT, IntermediateVT);
697 } else if (NumParts > 0) {
698 // If the intermediate type was expanded, build the intermediate operands
699 // from the parts.
Dan Gohman90cfc9d2007-07-30 19:09:17 +0000700 assert(NumParts % NumIntermediates == 0 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000701 "Must expand into a divisible number of parts!");
Dan Gohman90cfc9d2007-07-30 19:09:17 +0000702 unsigned Factor = NumParts / NumIntermediates;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000703 for (unsigned i = 0; i != NumIntermediates; ++i)
704 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
705 PartVT, IntermediateVT);
706 }
707
708 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
709 // operands.
710 return DAG.getNode(MVT::isVector(IntermediateVT) ?
711 ISD::CONCAT_VECTORS :
712 ISD::BUILD_VECTOR,
Dan Gohman90cfc9d2007-07-30 19:09:17 +0000713 ValueVT, &Ops[0], NumIntermediates);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714}
715
716/// getCopyToParts - Create a series of nodes that contain the
717/// specified value split into legal parts.
718static void getCopyToParts(SelectionDAG &DAG,
719 SDOperand Val,
720 SDOperand *Parts,
721 unsigned NumParts,
722 MVT::ValueType PartVT) {
Dan Gohmanf7b05132007-08-10 14:59:38 +0000723 TargetLowering &TLI = DAG.getTargetLoweringInfo();
724 MVT::ValueType PtrVT = TLI.getPointerTy();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000725 MVT::ValueType ValueVT = Val.getValueType();
726
727 if (!MVT::isVector(ValueVT) || NumParts == 1) {
728 // If the value was expanded, copy from the parts.
729 if (NumParts > 1) {
730 for (unsigned i = 0; i != NumParts; ++i)
731 Parts[i] = DAG.getNode(ISD::EXTRACT_ELEMENT, PartVT, Val,
Dan Gohmanf7b05132007-08-10 14:59:38 +0000732 DAG.getConstant(i, PtrVT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733 if (!DAG.getTargetLoweringInfo().isLittleEndian())
734 std::reverse(Parts, Parts + NumParts);
735 return;
736 }
737
738 // If there is a single part and the types differ, this must be
739 // a promotion.
740 if (PartVT != ValueVT) {
741 if (MVT::isVector(PartVT)) {
742 assert(MVT::isVector(ValueVT) &&
743 "Not a vector-vector cast?");
744 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
745 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
746 if (PartVT < ValueVT)
747 Val = DAG.getNode(ISD::TRUNCATE, PartVT, Val);
748 else
749 Val = DAG.getNode(ISD::ANY_EXTEND, PartVT, Val);
750 } else if (MVT::isFloatingPoint(PartVT) &&
751 MVT::isFloatingPoint(ValueVT)) {
752 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
753 } else if (MVT::getSizeInBits(PartVT) ==
754 MVT::getSizeInBits(ValueVT)) {
755 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
756 } else {
757 assert(0 && "Unknown mismatch!");
758 }
759 }
760 Parts[0] = Val;
761 return;
762 }
763
764 // Handle a multi-element vector.
765 MVT::ValueType IntermediateVT, RegisterVT;
766 unsigned NumIntermediates;
767 unsigned NumRegs =
768 DAG.getTargetLoweringInfo()
769 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
770 RegisterVT);
771 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
772
773 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
774 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
775
776 // Split the vector into intermediate operands.
777 SmallVector<SDOperand, 8> Ops(NumIntermediates);
778 for (unsigned i = 0; i != NumIntermediates; ++i)
779 if (MVT::isVector(IntermediateVT))
780 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
781 IntermediateVT, Val,
782 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohmanf7b05132007-08-10 14:59:38 +0000783 PtrVT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000784 else
785 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
786 IntermediateVT, Val,
Dan Gohmanf7b05132007-08-10 14:59:38 +0000787 DAG.getConstant(i, PtrVT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788
789 // Split the intermediate operands into legal parts.
790 if (NumParts == NumIntermediates) {
791 // If the register was not expanded, promote or copy the value,
792 // as appropriate.
793 for (unsigned i = 0; i != NumParts; ++i)
794 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
795 } else if (NumParts > 0) {
796 // If the intermediate type was expanded, split each the value into
797 // legal parts.
798 assert(NumParts % NumIntermediates == 0 &&
799 "Must expand into a divisible number of parts!");
800 unsigned Factor = NumParts / NumIntermediates;
801 for (unsigned i = 0; i != NumIntermediates; ++i)
802 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
803 }
804}
805
806
807SDOperand SelectionDAGLowering::getValue(const Value *V) {
808 SDOperand &N = NodeMap[V];
809 if (N.Val) return N;
810
811 const Type *VTy = V->getType();
812 MVT::ValueType VT = TLI.getValueType(VTy);
813 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
814 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
815 visit(CE->getOpcode(), *CE);
816 SDOperand N1 = NodeMap[V];
817 assert(N1.Val && "visit didn't populate the ValueMap!");
818 return N1;
819 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
820 return N = DAG.getGlobalAddress(GV, VT);
821 } else if (isa<ConstantPointerNull>(C)) {
822 return N = DAG.getConstant(0, TLI.getPointerTy());
823 } else if (isa<UndefValue>(C)) {
824 if (!isa<VectorType>(VTy))
825 return N = DAG.getNode(ISD::UNDEF, VT);
826
827 // Create a BUILD_VECTOR of undef nodes.
828 const VectorType *PTy = cast<VectorType>(VTy);
829 unsigned NumElements = PTy->getNumElements();
830 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
831
832 SmallVector<SDOperand, 8> Ops;
833 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
834
835 // Create a VConstant node with generic Vector type.
836 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
837 return N = DAG.getNode(ISD::BUILD_VECTOR, VT,
838 &Ops[0], Ops.size());
839 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
840 return N = DAG.getConstantFP(CFP->getValue(), VT);
841 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
842 unsigned NumElements = PTy->getNumElements();
843 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
844
845 // Now that we know the number and type of the elements, push a
846 // Constant or ConstantFP node onto the ops list for each element of
847 // the vector constant.
848 SmallVector<SDOperand, 8> Ops;
849 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
850 for (unsigned i = 0; i != NumElements; ++i)
851 Ops.push_back(getValue(CP->getOperand(i)));
852 } else {
853 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
854 SDOperand Op;
855 if (MVT::isFloatingPoint(PVT))
856 Op = DAG.getConstantFP(0, PVT);
857 else
858 Op = DAG.getConstant(0, PVT);
859 Ops.assign(NumElements, Op);
860 }
861
862 // Create a BUILD_VECTOR node.
863 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
864 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0],
865 Ops.size());
866 } else {
867 // Canonicalize all constant ints to be unsigned.
868 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
869 }
870 }
871
872 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
873 std::map<const AllocaInst*, int>::iterator SI =
874 FuncInfo.StaticAllocaMap.find(AI);
875 if (SI != FuncInfo.StaticAllocaMap.end())
876 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
877 }
878
879 unsigned InReg = FuncInfo.ValueMap[V];
880 assert(InReg && "Value not in map!");
881
882 MVT::ValueType RegisterVT = TLI.getRegisterType(VT);
883 unsigned NumRegs = TLI.getNumRegisters(VT);
884
885 std::vector<unsigned> Regs(NumRegs);
886 for (unsigned i = 0; i != NumRegs; ++i)
887 Regs[i] = InReg + i;
888
889 RegsForValue RFV(Regs, RegisterVT, VT);
890 SDOperand Chain = DAG.getEntryNode();
891
892 return RFV.getCopyFromRegs(DAG, Chain, NULL);
893}
894
895
896void SelectionDAGLowering::visitRet(ReturnInst &I) {
897 if (I.getNumOperands() == 0) {
898 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
899 return;
900 }
901 SmallVector<SDOperand, 8> NewValues;
902 NewValues.push_back(getRoot());
903 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
904 SDOperand RetOp = getValue(I.getOperand(i));
905
906 // If this is an integer return value, we need to promote it ourselves to
907 // the full width of a register, since getCopyToParts and Legalize will use
908 // ANY_EXTEND rather than sign/zero.
909 // FIXME: C calling convention requires the return type to be promoted to
910 // at least 32-bit. But this is not necessary for non-C calling conventions.
911 if (MVT::isInteger(RetOp.getValueType()) &&
912 RetOp.getValueType() < MVT::i64) {
913 MVT::ValueType TmpVT;
914 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
915 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
916 else
917 TmpVT = MVT::i32;
918 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
919 const ParamAttrsList *Attrs = FTy->getParamAttrs();
920 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
921 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
922 ExtendKind = ISD::SIGN_EXTEND;
923 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
924 ExtendKind = ISD::ZERO_EXTEND;
925 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
926 NewValues.push_back(RetOp);
927 NewValues.push_back(DAG.getConstant(false, MVT::i32));
928 } else {
929 MVT::ValueType VT = RetOp.getValueType();
930 unsigned NumParts = TLI.getNumRegisters(VT);
931 MVT::ValueType PartVT = TLI.getRegisterType(VT);
932 SmallVector<SDOperand, 4> Parts(NumParts);
933 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT);
934 for (unsigned i = 0; i < NumParts; ++i) {
935 NewValues.push_back(Parts[i]);
936 NewValues.push_back(DAG.getConstant(false, MVT::i32));
937 }
938 }
939 }
940 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
941 &NewValues[0], NewValues.size()));
942}
943
944/// ExportFromCurrentBlock - If this condition isn't known to be exported from
945/// the current basic block, add it to ValueMap now so that we'll get a
946/// CopyTo/FromReg.
947void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
948 // No need to export constants.
949 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
950
951 // Already exported?
952 if (FuncInfo.isExportedInst(V)) return;
953
954 unsigned Reg = FuncInfo.InitializeRegForValue(V);
955 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
956}
957
958bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
959 const BasicBlock *FromBB) {
960 // The operands of the setcc have to be in this block. We don't know
961 // how to export them from some other block.
962 if (Instruction *VI = dyn_cast<Instruction>(V)) {
963 // Can export from current BB.
964 if (VI->getParent() == FromBB)
965 return true;
966
967 // Is already exported, noop.
968 return FuncInfo.isExportedInst(V);
969 }
970
971 // If this is an argument, we can export it if the BB is the entry block or
972 // if it is already exported.
973 if (isa<Argument>(V)) {
974 if (FromBB == &FromBB->getParent()->getEntryBlock())
975 return true;
976
977 // Otherwise, can only export this if it is already exported.
978 return FuncInfo.isExportedInst(V);
979 }
980
981 // Otherwise, constants can always be exported.
982 return true;
983}
984
985static bool InBlock(const Value *V, const BasicBlock *BB) {
986 if (const Instruction *I = dyn_cast<Instruction>(V))
987 return I->getParent() == BB;
988 return true;
989}
990
991/// FindMergedConditions - If Cond is an expression like
992void SelectionDAGLowering::FindMergedConditions(Value *Cond,
993 MachineBasicBlock *TBB,
994 MachineBasicBlock *FBB,
995 MachineBasicBlock *CurBB,
996 unsigned Opc) {
997 // If this node is not part of the or/and tree, emit it as a branch.
998 Instruction *BOp = dyn_cast<Instruction>(Cond);
999
1000 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1001 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1002 BOp->getParent() != CurBB->getBasicBlock() ||
1003 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1004 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1005 const BasicBlock *BB = CurBB->getBasicBlock();
1006
1007 // If the leaf of the tree is a comparison, merge the condition into
1008 // the caseblock.
1009 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1010 // The operands of the cmp have to be in this block. We don't know
1011 // how to export them from some other block. If this is the first block
1012 // of the sequence, no exporting is needed.
1013 (CurBB == CurMBB ||
1014 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1015 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1016 BOp = cast<Instruction>(Cond);
1017 ISD::CondCode Condition;
1018 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1019 switch (IC->getPredicate()) {
1020 default: assert(0 && "Unknown icmp predicate opcode!");
1021 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1022 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1023 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1024 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1025 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1026 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1027 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1028 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1029 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1030 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1031 }
1032 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1033 ISD::CondCode FPC, FOC;
1034 switch (FC->getPredicate()) {
1035 default: assert(0 && "Unknown fcmp predicate opcode!");
1036 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1037 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1038 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1039 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1040 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1041 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1042 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1043 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1044 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1045 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1046 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1047 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1048 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1049 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1050 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1051 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1052 }
1053 if (FiniteOnlyFPMath())
1054 Condition = FOC;
1055 else
1056 Condition = FPC;
1057 } else {
1058 Condition = ISD::SETEQ; // silence warning.
1059 assert(0 && "Unknown compare instruction");
1060 }
1061
1062 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
1063 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1064 SwitchCases.push_back(CB);
1065 return;
1066 }
1067
1068 // Create a CaseBlock record representing this branch.
1069 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1070 NULL, TBB, FBB, CurBB);
1071 SwitchCases.push_back(CB);
1072 return;
1073 }
1074
1075
1076 // Create TmpBB after CurBB.
1077 MachineFunction::iterator BBI = CurBB;
1078 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1079 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1080
1081 if (Opc == Instruction::Or) {
1082 // Codegen X | Y as:
1083 // jmp_if_X TBB
1084 // jmp TmpBB
1085 // TmpBB:
1086 // jmp_if_Y TBB
1087 // jmp FBB
1088 //
1089
1090 // Emit the LHS condition.
1091 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1092
1093 // Emit the RHS condition into TmpBB.
1094 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1095 } else {
1096 assert(Opc == Instruction::And && "Unknown merge op!");
1097 // Codegen X & Y as:
1098 // jmp_if_X TmpBB
1099 // jmp FBB
1100 // TmpBB:
1101 // jmp_if_Y TBB
1102 // jmp FBB
1103 //
1104 // This requires creation of TmpBB after CurBB.
1105
1106 // Emit the LHS condition.
1107 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1108
1109 // Emit the RHS condition into TmpBB.
1110 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1111 }
1112}
1113
1114/// If the set of cases should be emitted as a series of branches, return true.
1115/// If we should emit this as a bunch of and/or'd together conditions, return
1116/// false.
1117static bool
1118ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1119 if (Cases.size() != 2) return true;
1120
1121 // If this is two comparisons of the same values or'd or and'd together, they
1122 // will get folded into a single comparison, so don't emit two blocks.
1123 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1124 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1125 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1126 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1127 return false;
1128 }
1129
1130 return true;
1131}
1132
1133void SelectionDAGLowering::visitBr(BranchInst &I) {
1134 // Update machine-CFG edges.
1135 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1136
1137 // Figure out which block is immediately after the current one.
1138 MachineBasicBlock *NextBlock = 0;
1139 MachineFunction::iterator BBI = CurMBB;
1140 if (++BBI != CurMBB->getParent()->end())
1141 NextBlock = BBI;
1142
1143 if (I.isUnconditional()) {
1144 // If this is not a fall-through branch, emit the branch.
1145 if (Succ0MBB != NextBlock)
1146 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1147 DAG.getBasicBlock(Succ0MBB)));
1148
1149 // Update machine-CFG edges.
1150 CurMBB->addSuccessor(Succ0MBB);
1151
1152 return;
1153 }
1154
1155 // If this condition is one of the special cases we handle, do special stuff
1156 // now.
1157 Value *CondVal = I.getCondition();
1158 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1159
1160 // If this is a series of conditions that are or'd or and'd together, emit
1161 // this as a sequence of branches instead of setcc's with and/or operations.
1162 // For example, instead of something like:
1163 // cmp A, B
1164 // C = seteq
1165 // cmp D, E
1166 // F = setle
1167 // or C, F
1168 // jnz foo
1169 // Emit:
1170 // cmp A, B
1171 // je foo
1172 // cmp D, E
1173 // jle foo
1174 //
1175 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1176 if (BOp->hasOneUse() &&
1177 (BOp->getOpcode() == Instruction::And ||
1178 BOp->getOpcode() == Instruction::Or)) {
1179 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1180 // If the compares in later blocks need to use values not currently
1181 // exported from this block, export them now. This block should always
1182 // be the first entry.
1183 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1184
1185 // Allow some cases to be rejected.
1186 if (ShouldEmitAsBranches(SwitchCases)) {
1187 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1188 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1189 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1190 }
1191
1192 // Emit the branch for this block.
1193 visitSwitchCase(SwitchCases[0]);
1194 SwitchCases.erase(SwitchCases.begin());
1195 return;
1196 }
1197
1198 // Okay, we decided not to do this, remove any inserted MBB's and clear
1199 // SwitchCases.
1200 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1201 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1202
1203 SwitchCases.clear();
1204 }
1205 }
1206
1207 // Create a CaseBlock record representing this branch.
1208 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1209 NULL, Succ0MBB, Succ1MBB, CurMBB);
1210 // Use visitSwitchCase to actually insert the fast branch sequence for this
1211 // cond branch.
1212 visitSwitchCase(CB);
1213}
1214
1215/// visitSwitchCase - Emits the necessary code to represent a single node in
1216/// the binary search tree resulting from lowering a switch instruction.
1217void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1218 SDOperand Cond;
1219 SDOperand CondLHS = getValue(CB.CmpLHS);
1220
1221 // Build the setcc now.
1222 if (CB.CmpMHS == NULL) {
1223 // Fold "(X == true)" to X and "(X == false)" to !X to
1224 // handle common cases produced by branch lowering.
1225 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1226 Cond = CondLHS;
1227 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1228 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1229 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1230 } else
1231 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1232 } else {
1233 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1234
1235 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1236 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1237
1238 SDOperand CmpOp = getValue(CB.CmpMHS);
1239 MVT::ValueType VT = CmpOp.getValueType();
1240
1241 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1242 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1243 } else {
1244 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1245 Cond = DAG.getSetCC(MVT::i1, SUB,
1246 DAG.getConstant(High-Low, VT), ISD::SETULE);
1247 }
1248
1249 }
1250
1251 // Set NextBlock to be the MBB immediately after the current one, if any.
1252 // This is used to avoid emitting unnecessary branches to the next block.
1253 MachineBasicBlock *NextBlock = 0;
1254 MachineFunction::iterator BBI = CurMBB;
1255 if (++BBI != CurMBB->getParent()->end())
1256 NextBlock = BBI;
1257
1258 // If the lhs block is the next block, invert the condition so that we can
1259 // fall through to the lhs instead of the rhs block.
1260 if (CB.TrueBB == NextBlock) {
1261 std::swap(CB.TrueBB, CB.FalseBB);
1262 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1263 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1264 }
1265 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
1266 DAG.getBasicBlock(CB.TrueBB));
1267 if (CB.FalseBB == NextBlock)
1268 DAG.setRoot(BrCond);
1269 else
1270 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1271 DAG.getBasicBlock(CB.FalseBB)));
1272 // Update successor info
1273 CurMBB->addSuccessor(CB.TrueBB);
1274 CurMBB->addSuccessor(CB.FalseBB);
1275}
1276
1277/// visitJumpTable - Emit JumpTable node in the current MBB
1278void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1279 // Emit the code for the jump table
1280 assert(JT.Reg != -1U && "Should lower JT Header first!");
1281 MVT::ValueType PTy = TLI.getPointerTy();
1282 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1283 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1284 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1285 Table, Index));
1286 return;
1287}
1288
1289/// visitJumpTableHeader - This function emits necessary code to produce index
1290/// in the JumpTable from switch case.
1291void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1292 SelectionDAGISel::JumpTableHeader &JTH) {
1293 // Subtract the lowest switch case value from the value being switched on
1294 // and conditional branch to default mbb if the result is greater than the
1295 // difference between smallest and largest cases.
1296 SDOperand SwitchOp = getValue(JTH.SValue);
1297 MVT::ValueType VT = SwitchOp.getValueType();
1298 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1299 DAG.getConstant(JTH.First, VT));
1300
1301 // The SDNode we just created, which holds the value being switched on
1302 // minus the the smallest case value, needs to be copied to a virtual
1303 // register so it can be used as an index into the jump table in a
1304 // subsequent basic block. This value may be smaller or larger than the
1305 // target's pointer type, and therefore require extension or truncating.
1306 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
1307 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1308 else
1309 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1310
1311 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1312 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1313 JT.Reg = JumpTableReg;
1314
1315 // Emit the range check for the jump table, and branch to the default
1316 // block for the switch statement if the value being switched on exceeds
1317 // the largest case in the switch.
1318 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1319 DAG.getConstant(JTH.Last-JTH.First,VT),
1320 ISD::SETUGT);
1321
1322 // Set NextBlock to be the MBB immediately after the current one, if any.
1323 // This is used to avoid emitting unnecessary branches to the next block.
1324 MachineBasicBlock *NextBlock = 0;
1325 MachineFunction::iterator BBI = CurMBB;
1326 if (++BBI != CurMBB->getParent()->end())
1327 NextBlock = BBI;
1328
1329 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1330 DAG.getBasicBlock(JT.Default));
1331
1332 if (JT.MBB == NextBlock)
1333 DAG.setRoot(BrCond);
1334 else
1335 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1336 DAG.getBasicBlock(JT.MBB)));
1337
1338 return;
1339}
1340
1341/// visitBitTestHeader - This function emits necessary code to produce value
1342/// suitable for "bit tests"
1343void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1344 // Subtract the minimum value
1345 SDOperand SwitchOp = getValue(B.SValue);
1346 MVT::ValueType VT = SwitchOp.getValueType();
1347 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1348 DAG.getConstant(B.First, VT));
1349
1350 // Check range
1351 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1352 DAG.getConstant(B.Range, VT),
1353 ISD::SETUGT);
1354
1355 SDOperand ShiftOp;
1356 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
1357 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1358 else
1359 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1360
1361 // Make desired shift
1362 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1363 DAG.getConstant(1, TLI.getPointerTy()),
1364 ShiftOp);
1365
1366 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1367 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1368 B.Reg = SwitchReg;
1369
1370 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1371 DAG.getBasicBlock(B.Default));
1372
1373 // Set NextBlock to be the MBB immediately after the current one, if any.
1374 // This is used to avoid emitting unnecessary branches to the next block.
1375 MachineBasicBlock *NextBlock = 0;
1376 MachineFunction::iterator BBI = CurMBB;
1377 if (++BBI != CurMBB->getParent()->end())
1378 NextBlock = BBI;
1379
1380 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1381 if (MBB == NextBlock)
1382 DAG.setRoot(BrRange);
1383 else
1384 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1385 DAG.getBasicBlock(MBB)));
1386
1387 CurMBB->addSuccessor(B.Default);
1388 CurMBB->addSuccessor(MBB);
1389
1390 return;
1391}
1392
1393/// visitBitTestCase - this function produces one "bit test"
1394void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1395 unsigned Reg,
1396 SelectionDAGISel::BitTestCase &B) {
1397 // Emit bit tests and jumps
1398 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1399
1400 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1401 SwitchVal,
1402 DAG.getConstant(B.Mask,
1403 TLI.getPointerTy()));
1404 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1405 DAG.getConstant(0, TLI.getPointerTy()),
1406 ISD::SETNE);
1407 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1408 AndCmp, DAG.getBasicBlock(B.TargetBB));
1409
1410 // Set NextBlock to be the MBB immediately after the current one, if any.
1411 // This is used to avoid emitting unnecessary branches to the next block.
1412 MachineBasicBlock *NextBlock = 0;
1413 MachineFunction::iterator BBI = CurMBB;
1414 if (++BBI != CurMBB->getParent()->end())
1415 NextBlock = BBI;
1416
1417 if (NextMBB == NextBlock)
1418 DAG.setRoot(BrAnd);
1419 else
1420 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1421 DAG.getBasicBlock(NextMBB)));
1422
1423 CurMBB->addSuccessor(B.TargetBB);
1424 CurMBB->addSuccessor(NextMBB);
1425
1426 return;
1427}
1428
1429void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1430 // Retrieve successors.
1431 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1432 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1433
1434 LowerCallTo(I, I.getCalledValue()->getType(),
1435 I.getCallingConv(),
1436 false,
1437 getValue(I.getOperand(0)),
1438 3, LandingPad);
1439
1440 // If the value of the invoke is used outside of its defining block, make it
1441 // available as a virtual register.
1442 if (!I.use_empty()) {
1443 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1444 if (VMI != FuncInfo.ValueMap.end())
1445 DAG.setRoot(CopyValueToVirtualRegister(&I, VMI->second));
1446 }
1447
1448 // Drop into normal successor.
1449 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1450 DAG.getBasicBlock(Return)));
1451
1452 // Update successor info
1453 CurMBB->addSuccessor(Return);
1454 CurMBB->addSuccessor(LandingPad);
1455}
1456
1457void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1458}
1459
1460/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1461/// small case ranges).
1462bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1463 CaseRecVector& WorkList,
1464 Value* SV,
1465 MachineBasicBlock* Default) {
1466 Case& BackCase = *(CR.Range.second-1);
1467
1468 // Size is the number of Cases represented by this range.
1469 unsigned Size = CR.Range.second - CR.Range.first;
1470 if (Size > 3)
1471 return false;
1472
1473 // Get the MachineFunction which holds the current MBB. This is used when
1474 // inserting any additional MBBs necessary to represent the switch.
1475 MachineFunction *CurMF = CurMBB->getParent();
1476
1477 // Figure out which block is immediately after the current one.
1478 MachineBasicBlock *NextBlock = 0;
1479 MachineFunction::iterator BBI = CR.CaseBB;
1480
1481 if (++BBI != CurMBB->getParent()->end())
1482 NextBlock = BBI;
1483
1484 // TODO: If any two of the cases has the same destination, and if one value
1485 // is the same as the other, but has one bit unset that the other has set,
1486 // use bit manipulation to do two compares at once. For example:
1487 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1488
1489 // Rearrange the case blocks so that the last one falls through if possible.
1490 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1491 // The last case block won't fall through into 'NextBlock' if we emit the
1492 // branches in this order. See if rearranging a case value would help.
1493 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1494 if (I->BB == NextBlock) {
1495 std::swap(*I, BackCase);
1496 break;
1497 }
1498 }
1499 }
1500
1501 // Create a CaseBlock record representing a conditional branch to
1502 // the Case's target mbb if the value being switched on SV is equal
1503 // to C.
1504 MachineBasicBlock *CurBlock = CR.CaseBB;
1505 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1506 MachineBasicBlock *FallThrough;
1507 if (I != E-1) {
1508 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1509 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1510 } else {
1511 // If the last case doesn't match, go to the default block.
1512 FallThrough = Default;
1513 }
1514
1515 Value *RHS, *LHS, *MHS;
1516 ISD::CondCode CC;
1517 if (I->High == I->Low) {
1518 // This is just small small case range :) containing exactly 1 case
1519 CC = ISD::SETEQ;
1520 LHS = SV; RHS = I->High; MHS = NULL;
1521 } else {
1522 CC = ISD::SETLE;
1523 LHS = I->Low; MHS = SV; RHS = I->High;
1524 }
1525 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1526 I->BB, FallThrough, CurBlock);
1527
1528 // If emitting the first comparison, just call visitSwitchCase to emit the
1529 // code into the current block. Otherwise, push the CaseBlock onto the
1530 // vector to be later processed by SDISel, and insert the node's MBB
1531 // before the next MBB.
1532 if (CurBlock == CurMBB)
1533 visitSwitchCase(CB);
1534 else
1535 SwitchCases.push_back(CB);
1536
1537 CurBlock = FallThrough;
1538 }
1539
1540 return true;
1541}
1542
1543static inline bool areJTsAllowed(const TargetLowering &TLI) {
1544 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1545 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1546}
1547
1548/// handleJTSwitchCase - Emit jumptable for current switch case range
1549bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1550 CaseRecVector& WorkList,
1551 Value* SV,
1552 MachineBasicBlock* Default) {
1553 Case& FrontCase = *CR.Range.first;
1554 Case& BackCase = *(CR.Range.second-1);
1555
1556 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1557 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1558
1559 uint64_t TSize = 0;
1560 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1561 I!=E; ++I)
1562 TSize += I->size();
1563
1564 if (!areJTsAllowed(TLI) || TSize <= 3)
1565 return false;
1566
1567 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1568 if (Density < 0.4)
1569 return false;
1570
1571 DOUT << "Lowering jump table\n"
1572 << "First entry: " << First << ". Last entry: " << Last << "\n"
1573 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1574
1575 // Get the MachineFunction which holds the current MBB. This is used when
1576 // inserting any additional MBBs necessary to represent the switch.
1577 MachineFunction *CurMF = CurMBB->getParent();
1578
1579 // Figure out which block is immediately after the current one.
1580 MachineBasicBlock *NextBlock = 0;
1581 MachineFunction::iterator BBI = CR.CaseBB;
1582
1583 if (++BBI != CurMBB->getParent()->end())
1584 NextBlock = BBI;
1585
1586 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1587
1588 // Create a new basic block to hold the code for loading the address
1589 // of the jump table, and jumping to it. Update successor information;
1590 // we will either branch to the default case for the switch, or the jump
1591 // table.
1592 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1593 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1594 CR.CaseBB->addSuccessor(Default);
1595 CR.CaseBB->addSuccessor(JumpTableBB);
1596
1597 // Build a vector of destination BBs, corresponding to each target
1598 // of the jump table. If the value of the jump table slot corresponds to
1599 // a case statement, push the case's BB onto the vector, otherwise, push
1600 // the default BB.
1601 std::vector<MachineBasicBlock*> DestBBs;
1602 int64_t TEI = First;
1603 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1604 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1605 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1606
1607 if ((Low <= TEI) && (TEI <= High)) {
1608 DestBBs.push_back(I->BB);
1609 if (TEI==High)
1610 ++I;
1611 } else {
1612 DestBBs.push_back(Default);
1613 }
1614 }
1615
1616 // Update successor info. Add one edge to each unique successor.
1617 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1618 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1619 E = DestBBs.end(); I != E; ++I) {
1620 if (!SuccsHandled[(*I)->getNumber()]) {
1621 SuccsHandled[(*I)->getNumber()] = true;
1622 JumpTableBB->addSuccessor(*I);
1623 }
1624 }
1625
1626 // Create a jump table index for this jump table, or return an existing
1627 // one.
1628 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1629
1630 // Set the jump table information so that we can codegen it as a second
1631 // MachineBasicBlock
1632 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1633 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1634 (CR.CaseBB == CurMBB));
1635 if (CR.CaseBB == CurMBB)
1636 visitJumpTableHeader(JT, JTH);
1637
1638 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
1639
1640 return true;
1641}
1642
1643/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1644/// 2 subtrees.
1645bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1646 CaseRecVector& WorkList,
1647 Value* SV,
1648 MachineBasicBlock* Default) {
1649 // Get the MachineFunction which holds the current MBB. This is used when
1650 // inserting any additional MBBs necessary to represent the switch.
1651 MachineFunction *CurMF = CurMBB->getParent();
1652
1653 // Figure out which block is immediately after the current one.
1654 MachineBasicBlock *NextBlock = 0;
1655 MachineFunction::iterator BBI = CR.CaseBB;
1656
1657 if (++BBI != CurMBB->getParent()->end())
1658 NextBlock = BBI;
1659
1660 Case& FrontCase = *CR.Range.first;
1661 Case& BackCase = *(CR.Range.second-1);
1662 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1663
1664 // Size is the number of Cases represented by this range.
1665 unsigned Size = CR.Range.second - CR.Range.first;
1666
1667 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1668 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1669 double FMetric = 0;
1670 CaseItr Pivot = CR.Range.first + Size/2;
1671
1672 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1673 // (heuristically) allow us to emit JumpTable's later.
1674 uint64_t TSize = 0;
1675 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1676 I!=E; ++I)
1677 TSize += I->size();
1678
1679 uint64_t LSize = FrontCase.size();
1680 uint64_t RSize = TSize-LSize;
1681 DOUT << "Selecting best pivot: \n"
1682 << "First: " << First << ", Last: " << Last <<"\n"
1683 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1684 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1685 J!=E; ++I, ++J) {
1686 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1687 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1688 assert((RBegin-LEnd>=1) && "Invalid case distance");
1689 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1690 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1691 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1692 // Should always split in some non-trivial place
1693 DOUT <<"=>Step\n"
1694 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1695 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1696 << "Metric: " << Metric << "\n";
1697 if (FMetric < Metric) {
1698 Pivot = J;
1699 FMetric = Metric;
1700 DOUT << "Current metric set to: " << FMetric << "\n";
1701 }
1702
1703 LSize += J->size();
1704 RSize -= J->size();
1705 }
1706 if (areJTsAllowed(TLI)) {
1707 // If our case is dense we *really* should handle it earlier!
1708 assert((FMetric > 0) && "Should handle dense range earlier!");
1709 } else {
1710 Pivot = CR.Range.first + Size/2;
1711 }
1712
1713 CaseRange LHSR(CR.Range.first, Pivot);
1714 CaseRange RHSR(Pivot, CR.Range.second);
1715 Constant *C = Pivot->Low;
1716 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1717
1718 // We know that we branch to the LHS if the Value being switched on is
1719 // less than the Pivot value, C. We use this to optimize our binary
1720 // tree a bit, by recognizing that if SV is greater than or equal to the
1721 // LHS's Case Value, and that Case Value is exactly one less than the
1722 // Pivot's Value, then we can branch directly to the LHS's Target,
1723 // rather than creating a leaf node for it.
1724 if ((LHSR.second - LHSR.first) == 1 &&
1725 LHSR.first->High == CR.GE &&
1726 cast<ConstantInt>(C)->getSExtValue() ==
1727 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1728 TrueBB = LHSR.first->BB;
1729 } else {
1730 TrueBB = new MachineBasicBlock(LLVMBB);
1731 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1732 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1733 }
1734
1735 // Similar to the optimization above, if the Value being switched on is
1736 // known to be less than the Constant CR.LT, and the current Case Value
1737 // is CR.LT - 1, then we can branch directly to the target block for
1738 // the current Case Value, rather than emitting a RHS leaf node for it.
1739 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1740 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1741 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1742 FalseBB = RHSR.first->BB;
1743 } else {
1744 FalseBB = new MachineBasicBlock(LLVMBB);
1745 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1746 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1747 }
1748
1749 // Create a CaseBlock record representing a conditional branch to
1750 // the LHS node if the value being switched on SV is less than C.
1751 // Otherwise, branch to LHS.
1752 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1753 TrueBB, FalseBB, CR.CaseBB);
1754
1755 if (CR.CaseBB == CurMBB)
1756 visitSwitchCase(CB);
1757 else
1758 SwitchCases.push_back(CB);
1759
1760 return true;
1761}
1762
1763/// handleBitTestsSwitchCase - if current case range has few destination and
1764/// range span less, than machine word bitwidth, encode case range into series
1765/// of masks and emit bit tests with these masks.
1766bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1767 CaseRecVector& WorkList,
1768 Value* SV,
1769 MachineBasicBlock* Default){
1770 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
1771
1772 Case& FrontCase = *CR.Range.first;
1773 Case& BackCase = *(CR.Range.second-1);
1774
1775 // Get the MachineFunction which holds the current MBB. This is used when
1776 // inserting any additional MBBs necessary to represent the switch.
1777 MachineFunction *CurMF = CurMBB->getParent();
1778
1779 unsigned numCmps = 0;
1780 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1781 I!=E; ++I) {
1782 // Single case counts one, case range - two.
1783 if (I->Low == I->High)
1784 numCmps +=1;
1785 else
1786 numCmps +=2;
1787 }
1788
1789 // Count unique destinations
1790 SmallSet<MachineBasicBlock*, 4> Dests;
1791 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1792 Dests.insert(I->BB);
1793 if (Dests.size() > 3)
1794 // Don't bother the code below, if there are too much unique destinations
1795 return false;
1796 }
1797 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1798 << "Total number of comparisons: " << numCmps << "\n";
1799
1800 // Compute span of values.
1801 Constant* minValue = FrontCase.Low;
1802 Constant* maxValue = BackCase.High;
1803 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1804 cast<ConstantInt>(minValue)->getSExtValue();
1805 DOUT << "Compare range: " << range << "\n"
1806 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1807 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1808
1809 if (range>=IntPtrBits ||
1810 (!(Dests.size() == 1 && numCmps >= 3) &&
1811 !(Dests.size() == 2 && numCmps >= 5) &&
1812 !(Dests.size() >= 3 && numCmps >= 6)))
1813 return false;
1814
1815 DOUT << "Emitting bit tests\n";
1816 int64_t lowBound = 0;
1817
1818 // Optimize the case where all the case values fit in a
1819 // word without having to subtract minValue. In this case,
1820 // we can optimize away the subtraction.
1821 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1822 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
1823 range = cast<ConstantInt>(maxValue)->getSExtValue();
1824 } else {
1825 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1826 }
1827
1828 CaseBitsVector CasesBits;
1829 unsigned i, count = 0;
1830
1831 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1832 MachineBasicBlock* Dest = I->BB;
1833 for (i = 0; i < count; ++i)
1834 if (Dest == CasesBits[i].BB)
1835 break;
1836
1837 if (i == count) {
1838 assert((count < 3) && "Too much destinations to test!");
1839 CasesBits.push_back(CaseBits(0, Dest, 0));
1840 count++;
1841 }
1842
1843 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1844 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1845
1846 for (uint64_t j = lo; j <= hi; j++) {
1847 CasesBits[i].Mask |= 1ULL << j;
1848 CasesBits[i].Bits++;
1849 }
1850
1851 }
1852 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1853
1854 SelectionDAGISel::BitTestInfo BTC;
1855
1856 // Figure out which block is immediately after the current one.
1857 MachineFunction::iterator BBI = CR.CaseBB;
1858 ++BBI;
1859
1860 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1861
1862 DOUT << "Cases:\n";
1863 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1864 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1865 << ", BB: " << CasesBits[i].BB << "\n";
1866
1867 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1868 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1869 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1870 CaseBB,
1871 CasesBits[i].BB));
1872 }
1873
1874 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
1875 -1U, (CR.CaseBB == CurMBB),
1876 CR.CaseBB, Default, BTC);
1877
1878 if (CR.CaseBB == CurMBB)
1879 visitBitTestHeader(BTB);
1880
1881 BitTestCases.push_back(BTB);
1882
1883 return true;
1884}
1885
1886
1887// Clusterify - Transform simple list of Cases into list of CaseRange's
1888unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1889 const SwitchInst& SI) {
1890 unsigned numCmps = 0;
1891
1892 // Start with "simple" cases
1893 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1894 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1895 Cases.push_back(Case(SI.getSuccessorValue(i),
1896 SI.getSuccessorValue(i),
1897 SMBB));
1898 }
1899 sort(Cases.begin(), Cases.end(), CaseCmp());
1900
1901 // Merge case into clusters
1902 if (Cases.size()>=2)
1903 // Must recompute end() each iteration because it may be
1904 // invalidated by erase if we hold on to it
1905 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
1906 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1907 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1908 MachineBasicBlock* nextBB = J->BB;
1909 MachineBasicBlock* currentBB = I->BB;
1910
1911 // If the two neighboring cases go to the same destination, merge them
1912 // into a single case.
1913 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1914 I->High = J->High;
1915 J = Cases.erase(J);
1916 } else {
1917 I = J++;
1918 }
1919 }
1920
1921 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1922 if (I->Low != I->High)
1923 // A range counts double, since it requires two compares.
1924 ++numCmps;
1925 }
1926
1927 return numCmps;
1928}
1929
1930void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1931 // Figure out which block is immediately after the current one.
1932 MachineBasicBlock *NextBlock = 0;
1933 MachineFunction::iterator BBI = CurMBB;
1934
1935 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1936
1937 // If there is only the default destination, branch to it if it is not the
1938 // next basic block. Otherwise, just fall through.
1939 if (SI.getNumOperands() == 2) {
1940 // Update machine-CFG edges.
1941
1942 // If this is not a fall-through branch, emit the branch.
1943 if (Default != NextBlock)
1944 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1945 DAG.getBasicBlock(Default)));
1946
1947 CurMBB->addSuccessor(Default);
1948 return;
1949 }
1950
1951 // If there are any non-default case statements, create a vector of Cases
1952 // representing each one, and sort the vector so that we can efficiently
1953 // create a binary search tree from them.
1954 CaseVector Cases;
1955 unsigned numCmps = Clusterify(Cases, SI);
1956 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1957 << ". Total compares: " << numCmps << "\n";
1958
1959 // Get the Value to be switched on and default basic blocks, which will be
1960 // inserted into CaseBlock records, representing basic blocks in the binary
1961 // search tree.
1962 Value *SV = SI.getOperand(0);
1963
1964 // Push the initial CaseRec onto the worklist
1965 CaseRecVector WorkList;
1966 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1967
1968 while (!WorkList.empty()) {
1969 // Grab a record representing a case range to process off the worklist
1970 CaseRec CR = WorkList.back();
1971 WorkList.pop_back();
1972
1973 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1974 continue;
1975
1976 // If the range has few cases (two or less) emit a series of specific
1977 // tests.
1978 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1979 continue;
1980
1981 // If the switch has more than 5 blocks, and at least 40% dense, and the
1982 // target supports indirect branches, then emit a jump table rather than
1983 // lowering the switch to a binary tree of conditional branches.
1984 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1985 continue;
1986
1987 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1988 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1989 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
1990 }
1991}
1992
1993
1994void SelectionDAGLowering::visitSub(User &I) {
1995 // -0.0 - X --> fneg
1996 const Type *Ty = I.getType();
1997 if (isa<VectorType>(Ty)) {
1998 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
1999 const VectorType *DestTy = cast<VectorType>(I.getType());
2000 const Type *ElTy = DestTy->getElementType();
2001 if (ElTy->isFloatingPoint()) {
2002 unsigned VL = DestTy->getNumElements();
2003 std::vector<Constant*> NZ(VL, ConstantFP::get(ElTy, -0.0));
2004 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2005 if (CV == CNZ) {
2006 SDOperand Op2 = getValue(I.getOperand(1));
2007 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2008 return;
2009 }
2010 }
2011 }
2012 }
2013 if (Ty->isFloatingPoint()) {
2014 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2015 if (CFP->isExactlyValue(-0.0)) {
2016 SDOperand Op2 = getValue(I.getOperand(1));
2017 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2018 return;
2019 }
2020 }
2021
2022 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2023}
2024
2025void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2026 SDOperand Op1 = getValue(I.getOperand(0));
2027 SDOperand Op2 = getValue(I.getOperand(1));
2028
2029 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2030}
2031
2032void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2033 SDOperand Op1 = getValue(I.getOperand(0));
2034 SDOperand Op2 = getValue(I.getOperand(1));
2035
2036 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2037 MVT::getSizeInBits(Op2.getValueType()))
2038 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2039 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2040 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2041
2042 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2043}
2044
2045void SelectionDAGLowering::visitICmp(User &I) {
2046 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2047 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2048 predicate = IC->getPredicate();
2049 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2050 predicate = ICmpInst::Predicate(IC->getPredicate());
2051 SDOperand Op1 = getValue(I.getOperand(0));
2052 SDOperand Op2 = getValue(I.getOperand(1));
2053 ISD::CondCode Opcode;
2054 switch (predicate) {
2055 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2056 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2057 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2058 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2059 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2060 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2061 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2062 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2063 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2064 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2065 default:
2066 assert(!"Invalid ICmp predicate value");
2067 Opcode = ISD::SETEQ;
2068 break;
2069 }
2070 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2071}
2072
2073void SelectionDAGLowering::visitFCmp(User &I) {
2074 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2075 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2076 predicate = FC->getPredicate();
2077 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2078 predicate = FCmpInst::Predicate(FC->getPredicate());
2079 SDOperand Op1 = getValue(I.getOperand(0));
2080 SDOperand Op2 = getValue(I.getOperand(1));
2081 ISD::CondCode Condition, FOC, FPC;
2082 switch (predicate) {
2083 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2084 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2085 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2086 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2087 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2088 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2089 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2090 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2091 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2092 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2093 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2094 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2095 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2096 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2097 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2098 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2099 default:
2100 assert(!"Invalid FCmp predicate value");
2101 FOC = FPC = ISD::SETFALSE;
2102 break;
2103 }
2104 if (FiniteOnlyFPMath())
2105 Condition = FOC;
2106 else
2107 Condition = FPC;
2108 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2109}
2110
2111void SelectionDAGLowering::visitSelect(User &I) {
2112 SDOperand Cond = getValue(I.getOperand(0));
2113 SDOperand TrueVal = getValue(I.getOperand(1));
2114 SDOperand FalseVal = getValue(I.getOperand(2));
2115 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2116 TrueVal, FalseVal));
2117}
2118
2119
2120void SelectionDAGLowering::visitTrunc(User &I) {
2121 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2122 SDOperand N = getValue(I.getOperand(0));
2123 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2124 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2125}
2126
2127void SelectionDAGLowering::visitZExt(User &I) {
2128 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2129 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2130 SDOperand N = getValue(I.getOperand(0));
2131 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2132 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2133}
2134
2135void SelectionDAGLowering::visitSExt(User &I) {
2136 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2137 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2138 SDOperand N = getValue(I.getOperand(0));
2139 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2140 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2141}
2142
2143void SelectionDAGLowering::visitFPTrunc(User &I) {
2144 // FPTrunc is never a no-op cast, no need to check
2145 SDOperand N = getValue(I.getOperand(0));
2146 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2147 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2148}
2149
2150void SelectionDAGLowering::visitFPExt(User &I){
2151 // FPTrunc is never a no-op cast, no need to check
2152 SDOperand N = getValue(I.getOperand(0));
2153 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2154 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2155}
2156
2157void SelectionDAGLowering::visitFPToUI(User &I) {
2158 // FPToUI is never a no-op cast, no need to check
2159 SDOperand N = getValue(I.getOperand(0));
2160 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2161 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2162}
2163
2164void SelectionDAGLowering::visitFPToSI(User &I) {
2165 // FPToSI is never a no-op cast, no need to check
2166 SDOperand N = getValue(I.getOperand(0));
2167 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2168 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2169}
2170
2171void SelectionDAGLowering::visitUIToFP(User &I) {
2172 // UIToFP is never a no-op cast, no need to check
2173 SDOperand N = getValue(I.getOperand(0));
2174 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2175 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2176}
2177
2178void SelectionDAGLowering::visitSIToFP(User &I){
2179 // UIToFP is never a no-op cast, no need to check
2180 SDOperand N = getValue(I.getOperand(0));
2181 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2182 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2183}
2184
2185void SelectionDAGLowering::visitPtrToInt(User &I) {
2186 // What to do depends on the size of the integer and the size of the pointer.
2187 // We can either truncate, zero extend, or no-op, accordingly.
2188 SDOperand N = getValue(I.getOperand(0));
2189 MVT::ValueType SrcVT = N.getValueType();
2190 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2191 SDOperand Result;
2192 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2193 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2194 else
2195 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2196 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2197 setValue(&I, Result);
2198}
2199
2200void SelectionDAGLowering::visitIntToPtr(User &I) {
2201 // What to do depends on the size of the integer and the size of the pointer.
2202 // We can either truncate, zero extend, or no-op, accordingly.
2203 SDOperand N = getValue(I.getOperand(0));
2204 MVT::ValueType SrcVT = N.getValueType();
2205 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2206 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2207 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2208 else
2209 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2210 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2211}
2212
2213void SelectionDAGLowering::visitBitCast(User &I) {
2214 SDOperand N = getValue(I.getOperand(0));
2215 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2216
2217 // BitCast assures us that source and destination are the same size so this
2218 // is either a BIT_CONVERT or a no-op.
2219 if (DestVT != N.getValueType())
2220 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2221 else
2222 setValue(&I, N); // noop cast.
2223}
2224
2225void SelectionDAGLowering::visitInsertElement(User &I) {
2226 SDOperand InVec = getValue(I.getOperand(0));
2227 SDOperand InVal = getValue(I.getOperand(1));
2228 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2229 getValue(I.getOperand(2)));
2230
2231 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2232 TLI.getValueType(I.getType()),
2233 InVec, InVal, InIdx));
2234}
2235
2236void SelectionDAGLowering::visitExtractElement(User &I) {
2237 SDOperand InVec = getValue(I.getOperand(0));
2238 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2239 getValue(I.getOperand(1)));
2240 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2241 TLI.getValueType(I.getType()), InVec, InIdx));
2242}
2243
2244void SelectionDAGLowering::visitShuffleVector(User &I) {
2245 SDOperand V1 = getValue(I.getOperand(0));
2246 SDOperand V2 = getValue(I.getOperand(1));
2247 SDOperand Mask = getValue(I.getOperand(2));
2248
2249 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2250 TLI.getValueType(I.getType()),
2251 V1, V2, Mask));
2252}
2253
2254
2255void SelectionDAGLowering::visitGetElementPtr(User &I) {
2256 SDOperand N = getValue(I.getOperand(0));
2257 const Type *Ty = I.getOperand(0)->getType();
2258
2259 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2260 OI != E; ++OI) {
2261 Value *Idx = *OI;
2262 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2263 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2264 if (Field) {
2265 // N = N + Offset
2266 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2267 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2268 getIntPtrConstant(Offset));
2269 }
2270 Ty = StTy->getElementType(Field);
2271 } else {
2272 Ty = cast<SequentialType>(Ty)->getElementType();
2273
2274 // If this is a constant subscript, handle it quickly.
2275 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2276 if (CI->getZExtValue() == 0) continue;
2277 uint64_t Offs =
2278 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2279 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2280 continue;
2281 }
2282
2283 // N = N + Idx * ElementSize;
2284 uint64_t ElementSize = TD->getTypeSize(Ty);
2285 SDOperand IdxN = getValue(Idx);
2286
2287 // If the index is smaller or larger than intptr_t, truncate or extend
2288 // it.
2289 if (IdxN.getValueType() < N.getValueType()) {
2290 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2291 } else if (IdxN.getValueType() > N.getValueType())
2292 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2293
2294 // If this is a multiply by a power of two, turn it into a shl
2295 // immediately. This is a very common case.
2296 if (isPowerOf2_64(ElementSize)) {
2297 unsigned Amt = Log2_64(ElementSize);
2298 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2299 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2300 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2301 continue;
2302 }
2303
2304 SDOperand Scale = getIntPtrConstant(ElementSize);
2305 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2306 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2307 }
2308 }
2309 setValue(&I, N);
2310}
2311
2312void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2313 // If this is a fixed sized alloca in the entry block of the function,
2314 // allocate it statically on the stack.
2315 if (FuncInfo.StaticAllocaMap.count(&I))
2316 return; // getValue will auto-populate this.
2317
2318 const Type *Ty = I.getAllocatedType();
2319 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
2320 unsigned Align =
2321 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2322 I.getAlignment());
2323
2324 SDOperand AllocSize = getValue(I.getArraySize());
2325 MVT::ValueType IntPtr = TLI.getPointerTy();
2326 if (IntPtr < AllocSize.getValueType())
2327 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2328 else if (IntPtr > AllocSize.getValueType())
2329 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2330
2331 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2332 getIntPtrConstant(TySize));
2333
Evan Chenga31dc752007-08-16 23:46:29 +00002334 // Handle alignment. If the requested alignment is less than or equal to
2335 // the stack alignment, ignore it. If the size is greater than or equal to
2336 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002337 unsigned StackAlign =
2338 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Chenga31dc752007-08-16 23:46:29 +00002339 if (Align <= StackAlign)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002340 Align = 0;
Evan Chenga31dc752007-08-16 23:46:29 +00002341
2342 // Round the size of the allocation up to the stack alignment size
2343 // by add SA-1 to the size.
2344 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2345 getIntPtrConstant(StackAlign-1));
2346 // Mask out the low bits for alignment purposes.
2347 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2348 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002349
2350 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
2351 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2352 MVT::Other);
2353 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2354 setValue(&I, DSA);
2355 DAG.setRoot(DSA.getValue(1));
2356
2357 // Inform the Frame Information that we have just allocated a variable-sized
2358 // object.
2359 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2360}
2361
2362void SelectionDAGLowering::visitLoad(LoadInst &I) {
2363 SDOperand Ptr = getValue(I.getOperand(0));
2364
2365 SDOperand Root;
2366 if (I.isVolatile())
2367 Root = getRoot();
2368 else {
2369 // Do not serialize non-volatile loads against each other.
2370 Root = DAG.getRoot();
2371 }
2372
2373 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
2374 Root, I.isVolatile(), I.getAlignment()));
2375}
2376
2377SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
2378 const Value *SV, SDOperand Root,
2379 bool isVolatile,
2380 unsigned Alignment) {
2381 SDOperand L =
2382 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2383 isVolatile, Alignment);
2384
2385 if (isVolatile)
2386 DAG.setRoot(L.getValue(1));
2387 else
2388 PendingLoads.push_back(L.getValue(1));
2389
2390 return L;
2391}
2392
2393
2394void SelectionDAGLowering::visitStore(StoreInst &I) {
2395 Value *SrcV = I.getOperand(0);
2396 SDOperand Src = getValue(SrcV);
2397 SDOperand Ptr = getValue(I.getOperand(1));
2398 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
2399 I.isVolatile(), I.getAlignment()));
2400}
2401
2402/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2403/// access memory and has no other side effects at all.
2404static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2405#define GET_NO_MEMORY_INTRINSICS
2406#include "llvm/Intrinsics.gen"
2407#undef GET_NO_MEMORY_INTRINSICS
2408 return false;
2409}
2410
2411// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2412// have any side-effects or if it only reads memory.
2413static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2414#define GET_SIDE_EFFECT_INFO
2415#include "llvm/Intrinsics.gen"
2416#undef GET_SIDE_EFFECT_INFO
2417 return false;
2418}
2419
2420/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2421/// node.
2422void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2423 unsigned Intrinsic) {
2424 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
2425 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
2426
2427 // Build the operand list.
2428 SmallVector<SDOperand, 8> Ops;
2429 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2430 if (OnlyLoad) {
2431 // We don't need to serialize loads against other loads.
2432 Ops.push_back(DAG.getRoot());
2433 } else {
2434 Ops.push_back(getRoot());
2435 }
2436 }
2437
2438 // Add the intrinsic ID as an integer operand.
2439 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2440
2441 // Add all operands of the call to the operand list.
2442 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2443 SDOperand Op = getValue(I.getOperand(i));
2444 assert(TLI.isTypeLegal(Op.getValueType()) &&
2445 "Intrinsic uses a non-legal type?");
2446 Ops.push_back(Op);
2447 }
2448
2449 std::vector<MVT::ValueType> VTs;
2450 if (I.getType() != Type::VoidTy) {
2451 MVT::ValueType VT = TLI.getValueType(I.getType());
2452 if (MVT::isVector(VT)) {
2453 const VectorType *DestTy = cast<VectorType>(I.getType());
2454 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2455
2456 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2457 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2458 }
2459
2460 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2461 VTs.push_back(VT);
2462 }
2463 if (HasChain)
2464 VTs.push_back(MVT::Other);
2465
2466 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2467
2468 // Create the node.
2469 SDOperand Result;
2470 if (!HasChain)
2471 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2472 &Ops[0], Ops.size());
2473 else if (I.getType() != Type::VoidTy)
2474 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2475 &Ops[0], Ops.size());
2476 else
2477 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2478 &Ops[0], Ops.size());
2479
2480 if (HasChain) {
2481 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2482 if (OnlyLoad)
2483 PendingLoads.push_back(Chain);
2484 else
2485 DAG.setRoot(Chain);
2486 }
2487 if (I.getType() != Type::VoidTy) {
2488 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2489 MVT::ValueType VT = TLI.getValueType(PTy);
2490 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2491 }
2492 setValue(&I, Result);
2493 }
2494}
2495
2496/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2497static GlobalVariable *ExtractTypeInfo (Value *V) {
2498 V = IntrinsicInst::StripPointerCasts(V);
2499 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2500 assert (GV || isa<ConstantPointerNull>(V) &&
2501 "TypeInfo must be a global variable or NULL");
2502 return GV;
2503}
2504
2505/// addCatchInfo - Extract the personality and type infos from an eh.selector
2506/// call, and add them to the specified machine basic block.
2507static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2508 MachineBasicBlock *MBB) {
2509 // Inform the MachineModuleInfo of the personality for this landing pad.
2510 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2511 assert(CE->getOpcode() == Instruction::BitCast &&
2512 isa<Function>(CE->getOperand(0)) &&
2513 "Personality should be a function");
2514 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2515
2516 // Gather all the type infos for this landing pad and pass them along to
2517 // MachineModuleInfo.
2518 std::vector<GlobalVariable *> TyInfo;
2519 unsigned N = I.getNumOperands();
2520
2521 for (unsigned i = N - 1; i > 2; --i) {
2522 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2523 unsigned FilterLength = CI->getZExtValue();
Duncan Sands923fdb12007-08-27 15:47:50 +00002524 unsigned FirstCatch = i + FilterLength + !FilterLength;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002525 assert (FirstCatch <= N && "Invalid filter length");
2526
2527 if (FirstCatch < N) {
2528 TyInfo.reserve(N - FirstCatch);
2529 for (unsigned j = FirstCatch; j < N; ++j)
2530 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2531 MMI->addCatchTypeInfo(MBB, TyInfo);
2532 TyInfo.clear();
2533 }
2534
Duncan Sands923fdb12007-08-27 15:47:50 +00002535 if (!FilterLength) {
2536 // Cleanup.
2537 MMI->addCleanup(MBB);
2538 } else {
2539 // Filter.
2540 TyInfo.reserve(FilterLength - 1);
2541 for (unsigned j = i + 1; j < FirstCatch; ++j)
2542 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2543 MMI->addFilterTypeInfo(MBB, TyInfo);
2544 TyInfo.clear();
2545 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002546
2547 N = i;
2548 }
2549 }
2550
2551 if (N > 3) {
2552 TyInfo.reserve(N - 3);
2553 for (unsigned j = 3; j < N; ++j)
2554 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2555 MMI->addCatchTypeInfo(MBB, TyInfo);
2556 }
2557}
2558
2559/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2560/// we want to emit this as a call to a named external function, return the name
2561/// otherwise lower it and return null.
2562const char *
2563SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2564 switch (Intrinsic) {
2565 default:
2566 // By default, turn this into a target intrinsic node.
2567 visitTargetIntrinsic(I, Intrinsic);
2568 return 0;
2569 case Intrinsic::vastart: visitVAStart(I); return 0;
2570 case Intrinsic::vaend: visitVAEnd(I); return 0;
2571 case Intrinsic::vacopy: visitVACopy(I); return 0;
2572 case Intrinsic::returnaddress:
2573 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2574 getValue(I.getOperand(1))));
2575 return 0;
2576 case Intrinsic::frameaddress:
2577 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2578 getValue(I.getOperand(1))));
2579 return 0;
2580 case Intrinsic::setjmp:
2581 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2582 break;
2583 case Intrinsic::longjmp:
2584 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2585 break;
2586 case Intrinsic::memcpy_i32:
2587 case Intrinsic::memcpy_i64:
2588 visitMemIntrinsic(I, ISD::MEMCPY);
2589 return 0;
2590 case Intrinsic::memset_i32:
2591 case Intrinsic::memset_i64:
2592 visitMemIntrinsic(I, ISD::MEMSET);
2593 return 0;
2594 case Intrinsic::memmove_i32:
2595 case Intrinsic::memmove_i64:
2596 visitMemIntrinsic(I, ISD::MEMMOVE);
2597 return 0;
2598
2599 case Intrinsic::dbg_stoppoint: {
2600 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2601 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2602 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2603 SDOperand Ops[5];
2604
2605 Ops[0] = getRoot();
2606 Ops[1] = getValue(SPI.getLineValue());
2607 Ops[2] = getValue(SPI.getColumnValue());
2608
2609 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2610 assert(DD && "Not a debug information descriptor");
2611 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2612
2613 Ops[3] = DAG.getString(CompileUnit->getFileName());
2614 Ops[4] = DAG.getString(CompileUnit->getDirectory());
2615
2616 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
2617 }
2618
2619 return 0;
2620 }
2621 case Intrinsic::dbg_region_start: {
2622 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2623 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2624 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2625 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2626 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2627 DAG.getConstant(LabelID, MVT::i32)));
2628 }
2629
2630 return 0;
2631 }
2632 case Intrinsic::dbg_region_end: {
2633 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2634 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2635 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2636 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2637 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2638 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2639 }
2640
2641 return 0;
2642 }
2643 case Intrinsic::dbg_func_start: {
2644 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2645 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2646 if (MMI && FSI.getSubprogram() &&
2647 MMI->Verify(FSI.getSubprogram())) {
2648 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
2649 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2650 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2651 }
2652
2653 return 0;
2654 }
2655 case Intrinsic::dbg_declare: {
2656 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2657 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2658 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
2659 SDOperand AddressOp = getValue(DI.getAddress());
2660 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
2661 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
2662 }
2663
2664 return 0;
2665 }
2666
2667 case Intrinsic::eh_exception: {
2668 if (ExceptionHandling) {
2669 if (!CurMBB->isLandingPad()) {
2670 // FIXME: Mark exception register as live in. Hack for PR1508.
2671 unsigned Reg = TLI.getExceptionAddressRegister();
2672 if (Reg) CurMBB->addLiveIn(Reg);
2673 }
2674 // Insert the EXCEPTIONADDR instruction.
2675 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2676 SDOperand Ops[1];
2677 Ops[0] = DAG.getRoot();
2678 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2679 setValue(&I, Op);
2680 DAG.setRoot(Op.getValue(1));
2681 } else {
2682 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2683 }
2684 return 0;
2685 }
2686
2687 case Intrinsic::eh_selector:{
2688 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2689
2690 if (ExceptionHandling && MMI) {
2691 if (CurMBB->isLandingPad())
2692 addCatchInfo(I, MMI, CurMBB);
2693 else {
2694#ifndef NDEBUG
2695 FuncInfo.CatchInfoLost.insert(&I);
2696#endif
2697 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2698 unsigned Reg = TLI.getExceptionSelectorRegister();
2699 if (Reg) CurMBB->addLiveIn(Reg);
2700 }
2701
2702 // Insert the EHSELECTION instruction.
2703 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2704 SDOperand Ops[2];
2705 Ops[0] = getValue(I.getOperand(1));
2706 Ops[1] = getRoot();
2707 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2708 setValue(&I, Op);
2709 DAG.setRoot(Op.getValue(1));
2710 } else {
2711 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2712 }
2713
2714 return 0;
2715 }
2716
2717 case Intrinsic::eh_typeid_for: {
2718 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2719
2720 if (MMI) {
2721 // Find the type id for the given typeinfo.
2722 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
2723
2724 unsigned TypeID = MMI->getTypeIDFor(GV);
2725 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
2726 } else {
2727 // Return something different to eh_selector.
2728 setValue(&I, DAG.getConstant(1, MVT::i32));
2729 }
2730
2731 return 0;
2732 }
2733
2734 case Intrinsic::eh_return: {
2735 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2736
2737 if (MMI && ExceptionHandling) {
2738 MMI->setCallsEHReturn(true);
2739 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
2740 MVT::Other,
2741 getRoot(),
2742 getValue(I.getOperand(1)),
2743 getValue(I.getOperand(2))));
2744 } else {
2745 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2746 }
2747
2748 return 0;
2749 }
2750
2751 case Intrinsic::eh_unwind_init: {
2752 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
2753 MMI->setCallsUnwindInit(true);
2754 }
2755
2756 return 0;
2757 }
2758
2759 case Intrinsic::eh_dwarf_cfa: {
2760 if (ExceptionHandling) {
2761 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
Anton Korobeynikovb5641a02007-08-23 07:21:06 +00002762 SDOperand CfaArg;
2763 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
2764 CfaArg = DAG.getNode(ISD::TRUNCATE,
2765 TLI.getPointerTy(), getValue(I.getOperand(1)));
2766 else
2767 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
2768 TLI.getPointerTy(), getValue(I.getOperand(1)));
2769
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002770 SDOperand Offset = DAG.getNode(ISD::ADD,
2771 TLI.getPointerTy(),
2772 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
Anton Korobeynikovb5641a02007-08-23 07:21:06 +00002773 TLI.getPointerTy()),
2774 CfaArg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002775 setValue(&I, DAG.getNode(ISD::ADD,
2776 TLI.getPointerTy(),
2777 DAG.getNode(ISD::FRAMEADDR,
2778 TLI.getPointerTy(),
2779 DAG.getConstant(0,
2780 TLI.getPointerTy())),
2781 Offset));
2782 } else {
2783 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2784 }
2785
2786 return 0;
2787 }
2788
2789 case Intrinsic::sqrt_f32:
2790 case Intrinsic::sqrt_f64:
2791 setValue(&I, DAG.getNode(ISD::FSQRT,
2792 getValue(I.getOperand(1)).getValueType(),
2793 getValue(I.getOperand(1))));
2794 return 0;
2795 case Intrinsic::powi_f32:
2796 case Intrinsic::powi_f64:
2797 setValue(&I, DAG.getNode(ISD::FPOWI,
2798 getValue(I.getOperand(1)).getValueType(),
2799 getValue(I.getOperand(1)),
2800 getValue(I.getOperand(2))));
2801 return 0;
2802 case Intrinsic::pcmarker: {
2803 SDOperand Tmp = getValue(I.getOperand(1));
2804 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2805 return 0;
2806 }
2807 case Intrinsic::readcyclecounter: {
2808 SDOperand Op = getRoot();
2809 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2810 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2811 &Op, 1);
2812 setValue(&I, Tmp);
2813 DAG.setRoot(Tmp.getValue(1));
2814 return 0;
2815 }
2816 case Intrinsic::part_select: {
2817 // Currently not implemented: just abort
2818 assert(0 && "part_select intrinsic not implemented");
2819 abort();
2820 }
2821 case Intrinsic::part_set: {
2822 // Currently not implemented: just abort
2823 assert(0 && "part_set intrinsic not implemented");
2824 abort();
2825 }
2826 case Intrinsic::bswap:
2827 setValue(&I, DAG.getNode(ISD::BSWAP,
2828 getValue(I.getOperand(1)).getValueType(),
2829 getValue(I.getOperand(1))));
2830 return 0;
2831 case Intrinsic::cttz: {
2832 SDOperand Arg = getValue(I.getOperand(1));
2833 MVT::ValueType Ty = Arg.getValueType();
2834 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002835 setValue(&I, result);
2836 return 0;
2837 }
2838 case Intrinsic::ctlz: {
2839 SDOperand Arg = getValue(I.getOperand(1));
2840 MVT::ValueType Ty = Arg.getValueType();
2841 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002842 setValue(&I, result);
2843 return 0;
2844 }
2845 case Intrinsic::ctpop: {
2846 SDOperand Arg = getValue(I.getOperand(1));
2847 MVT::ValueType Ty = Arg.getValueType();
2848 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002849 setValue(&I, result);
2850 return 0;
2851 }
2852 case Intrinsic::stacksave: {
2853 SDOperand Op = getRoot();
2854 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2855 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
2856 setValue(&I, Tmp);
2857 DAG.setRoot(Tmp.getValue(1));
2858 return 0;
2859 }
2860 case Intrinsic::stackrestore: {
2861 SDOperand Tmp = getValue(I.getOperand(1));
2862 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
2863 return 0;
2864 }
2865 case Intrinsic::prefetch:
2866 // FIXME: Currently discarding prefetches.
2867 return 0;
2868
2869 case Intrinsic::var_annotation:
2870 // Discard annotate attributes
2871 return 0;
Duncan Sands38947cd2007-07-27 12:58:54 +00002872
2873 case Intrinsic::adjust_trampoline: {
2874 SDOperand Arg = getValue(I.getOperand(1));
2875 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMP, TLI.getPointerTy(), Arg));
2876 return 0;
2877 }
2878
2879 case Intrinsic::init_trampoline: {
2880 const Function *F =
2881 cast<Function>(IntrinsicInst::StripPointerCasts(I.getOperand(2)));
2882
2883 SDOperand Ops[6];
2884 Ops[0] = getRoot();
2885 Ops[1] = getValue(I.getOperand(1));
2886 Ops[2] = getValue(I.getOperand(2));
2887 Ops[3] = getValue(I.getOperand(3));
2888 Ops[4] = DAG.getSrcValue(I.getOperand(1));
2889 Ops[5] = DAG.getSrcValue(F);
2890
2891 DAG.setRoot(DAG.getNode(ISD::TRAMPOLINE, MVT::Other, Ops, 6));
2892 return 0;
2893 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002894 }
2895}
2896
2897
2898void SelectionDAGLowering::LowerCallTo(Instruction &I,
2899 const Type *CalledValueTy,
2900 unsigned CallingConv,
2901 bool IsTailCall,
2902 SDOperand Callee, unsigned OpIdx,
2903 MachineBasicBlock *LandingPad) {
2904 const PointerType *PT = cast<PointerType>(CalledValueTy);
2905 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2906 const ParamAttrsList *Attrs = FTy->getParamAttrs();
2907 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2908 unsigned BeginLabel = 0, EndLabel = 0;
2909
2910 TargetLowering::ArgListTy Args;
2911 TargetLowering::ArgListEntry Entry;
2912 Args.reserve(I.getNumOperands());
2913 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2914 Value *Arg = I.getOperand(i);
2915 SDOperand ArgNode = getValue(Arg);
2916 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2917
2918 unsigned attrInd = i - OpIdx + 1;
2919 Entry.isSExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::SExt);
2920 Entry.isZExt = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ZExt);
2921 Entry.isInReg = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::InReg);
2922 Entry.isSRet = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::StructRet);
Duncan Sands38947cd2007-07-27 12:58:54 +00002923 Entry.isNest = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::Nest);
Rafael Espindolab8bcfcd2007-08-20 15:18:24 +00002924 Entry.isByVal = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ByVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002925 Args.push_back(Entry);
2926 }
2927
2928 if (ExceptionHandling && MMI) {
2929 // Insert a label before the invoke call to mark the try range. This can be
2930 // used to detect deletion of the invoke via the MachineModuleInfo.
2931 BeginLabel = MMI->NextLabelID();
2932 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2933 DAG.getConstant(BeginLabel, MVT::i32)));
2934 }
2935
2936 std::pair<SDOperand,SDOperand> Result =
2937 TLI.LowerCallTo(getRoot(), I.getType(),
2938 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
2939 FTy->isVarArg(), CallingConv, IsTailCall,
2940 Callee, Args, DAG);
2941 if (I.getType() != Type::VoidTy)
2942 setValue(&I, Result.first);
2943 DAG.setRoot(Result.second);
2944
2945 if (ExceptionHandling && MMI) {
2946 // Insert a label at the end of the invoke call to mark the try range. This
2947 // can be used to detect deletion of the invoke via the MachineModuleInfo.
2948 EndLabel = MMI->NextLabelID();
2949 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2950 DAG.getConstant(EndLabel, MVT::i32)));
2951
2952 // Inform MachineModuleInfo of range.
2953 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
2954 }
2955}
2956
2957
2958void SelectionDAGLowering::visitCall(CallInst &I) {
2959 const char *RenameFn = 0;
2960 if (Function *F = I.getCalledFunction()) {
2961 if (F->isDeclaration())
2962 if (unsigned IID = F->getIntrinsicID()) {
2963 RenameFn = visitIntrinsicCall(I, IID);
2964 if (!RenameFn)
2965 return;
2966 } else { // Not an LLVM intrinsic.
2967 const std::string &Name = F->getName();
2968 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2969 if (I.getNumOperands() == 3 && // Basic sanity checks.
2970 I.getOperand(1)->getType()->isFloatingPoint() &&
2971 I.getType() == I.getOperand(1)->getType() &&
2972 I.getType() == I.getOperand(2)->getType()) {
2973 SDOperand LHS = getValue(I.getOperand(1));
2974 SDOperand RHS = getValue(I.getOperand(2));
2975 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2976 LHS, RHS));
2977 return;
2978 }
2979 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
2980 if (I.getNumOperands() == 2 && // Basic sanity checks.
2981 I.getOperand(1)->getType()->isFloatingPoint() &&
2982 I.getType() == I.getOperand(1)->getType()) {
2983 SDOperand Tmp = getValue(I.getOperand(1));
2984 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2985 return;
2986 }
2987 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
2988 if (I.getNumOperands() == 2 && // Basic sanity checks.
2989 I.getOperand(1)->getType()->isFloatingPoint() &&
2990 I.getType() == I.getOperand(1)->getType()) {
2991 SDOperand Tmp = getValue(I.getOperand(1));
2992 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2993 return;
2994 }
2995 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
2996 if (I.getNumOperands() == 2 && // Basic sanity checks.
2997 I.getOperand(1)->getType()->isFloatingPoint() &&
2998 I.getType() == I.getOperand(1)->getType()) {
2999 SDOperand Tmp = getValue(I.getOperand(1));
3000 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3001 return;
3002 }
3003 }
3004 }
3005 } else if (isa<InlineAsm>(I.getOperand(0))) {
3006 visitInlineAsm(I);
3007 return;
3008 }
3009
3010 SDOperand Callee;
3011 if (!RenameFn)
3012 Callee = getValue(I.getOperand(0));
3013 else
3014 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3015
3016 LowerCallTo(I, I.getCalledValue()->getType(),
3017 I.getCallingConv(),
3018 I.isTailCall(),
3019 Callee,
3020 1);
3021}
3022
3023
3024/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3025/// this value and returns the result as a ValueVT value. This uses
3026/// Chain/Flag as the input and updates them for the output Chain/Flag.
3027/// If the Flag pointer is NULL, no flag is used.
3028SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3029 SDOperand &Chain, SDOperand *Flag)const{
3030 // Copy the legal parts from the registers.
3031 unsigned NumParts = Regs.size();
3032 SmallVector<SDOperand, 8> Parts(NumParts);
3033 for (unsigned i = 0; i != NumParts; ++i) {
3034 SDOperand Part = Flag ?
3035 DAG.getCopyFromReg(Chain, Regs[i], RegVT, *Flag) :
3036 DAG.getCopyFromReg(Chain, Regs[i], RegVT);
3037 Chain = Part.getValue(1);
3038 if (Flag)
3039 *Flag = Part.getValue(2);
3040 Parts[i] = Part;
3041 }
3042
3043 // Assemble the legal parts into the final value.
3044 return getCopyFromParts(DAG, &Parts[0], NumParts, RegVT, ValueVT);
3045}
3046
3047/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3048/// specified value into the registers specified by this object. This uses
3049/// Chain/Flag as the input and updates them for the output Chain/Flag.
3050/// If the Flag pointer is NULL, no flag is used.
3051void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
3052 SDOperand &Chain, SDOperand *Flag) const {
3053 // Get the list of the values's legal parts.
3054 unsigned NumParts = Regs.size();
3055 SmallVector<SDOperand, 8> Parts(NumParts);
3056 getCopyToParts(DAG, Val, &Parts[0], NumParts, RegVT);
3057
3058 // Copy the parts into the registers.
3059 for (unsigned i = 0; i != NumParts; ++i) {
3060 SDOperand Part = Flag ?
3061 DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag) :
3062 DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3063 Chain = Part.getValue(0);
3064 if (Flag)
3065 *Flag = Part.getValue(1);
3066 }
3067}
3068
3069/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3070/// operand list. This adds the code marker and includes the number of
3071/// values added into it.
3072void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3073 std::vector<SDOperand> &Ops) const {
3074 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3075 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3076 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
3077 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
3078}
3079
3080/// isAllocatableRegister - If the specified register is safe to allocate,
3081/// i.e. it isn't a stack pointer or some other special register, return the
3082/// register class for the register. Otherwise, return null.
3083static const TargetRegisterClass *
3084isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3085 const TargetLowering &TLI, const MRegisterInfo *MRI) {
3086 MVT::ValueType FoundVT = MVT::Other;
3087 const TargetRegisterClass *FoundRC = 0;
3088 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
3089 E = MRI->regclass_end(); RCI != E; ++RCI) {
3090 MVT::ValueType ThisVT = MVT::Other;
3091
3092 const TargetRegisterClass *RC = *RCI;
3093 // If none of the the value types for this register class are valid, we
3094 // can't use it. For example, 64-bit reg classes on 32-bit targets.
3095 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3096 I != E; ++I) {
3097 if (TLI.isTypeLegal(*I)) {
3098 // If we have already found this register in a different register class,
3099 // choose the one with the largest VT specified. For example, on
3100 // PowerPC, we favor f64 register classes over f32.
3101 if (FoundVT == MVT::Other ||
3102 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3103 ThisVT = *I;
3104 break;
3105 }
3106 }
3107 }
3108
3109 if (ThisVT == MVT::Other) continue;
3110
3111 // NOTE: This isn't ideal. In particular, this might allocate the
3112 // frame pointer in functions that need it (due to them not being taken
3113 // out of allocation, because a variable sized allocation hasn't been seen
3114 // yet). This is a slight code pessimization, but should still work.
3115 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3116 E = RC->allocation_order_end(MF); I != E; ++I)
3117 if (*I == Reg) {
3118 // We found a matching register class. Keep looking at others in case
3119 // we find one with larger registers that this physreg is also in.
3120 FoundRC = RC;
3121 FoundVT = ThisVT;
3122 break;
3123 }
3124 }
3125 return FoundRC;
3126}
3127
3128
3129namespace {
3130/// AsmOperandInfo - This contains information for each constraint that we are
3131/// lowering.
3132struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
3133 /// ConstraintCode - This contains the actual string for the code, like "m".
3134 std::string ConstraintCode;
3135
3136 /// ConstraintType - Information about the constraint code, e.g. Register,
3137 /// RegisterClass, Memory, Other, Unknown.
3138 TargetLowering::ConstraintType ConstraintType;
3139
3140 /// CallOperand/CallOperandval - If this is the result output operand or a
3141 /// clobber, this is null, otherwise it is the incoming operand to the
3142 /// CallInst. This gets modified as the asm is processed.
3143 SDOperand CallOperand;
3144 Value *CallOperandVal;
3145
3146 /// ConstraintVT - The ValueType for the operand value.
3147 MVT::ValueType ConstraintVT;
3148
3149 /// AssignedRegs - If this is a register or register class operand, this
3150 /// contains the set of register corresponding to the operand.
3151 RegsForValue AssignedRegs;
3152
3153 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3154 : InlineAsm::ConstraintInfo(info),
3155 ConstraintType(TargetLowering::C_Unknown),
3156 CallOperand(0,0), CallOperandVal(0), ConstraintVT(MVT::Other) {
3157 }
3158
3159 void ComputeConstraintToUse(const TargetLowering &TLI);
3160
3161 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3162 /// busy in OutputRegs/InputRegs.
3163 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3164 std::set<unsigned> &OutputRegs,
3165 std::set<unsigned> &InputRegs) const {
3166 if (isOutReg)
3167 OutputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3168 if (isInReg)
3169 InputRegs.insert(AssignedRegs.Regs.begin(), AssignedRegs.Regs.end());
3170 }
3171};
3172} // end anon namespace.
3173
3174/// getConstraintGenerality - Return an integer indicating how general CT is.
3175static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3176 switch (CT) {
3177 default: assert(0 && "Unknown constraint type!");
3178 case TargetLowering::C_Other:
3179 case TargetLowering::C_Unknown:
3180 return 0;
3181 case TargetLowering::C_Register:
3182 return 1;
3183 case TargetLowering::C_RegisterClass:
3184 return 2;
3185 case TargetLowering::C_Memory:
3186 return 3;
3187 }
3188}
3189
3190void AsmOperandInfo::ComputeConstraintToUse(const TargetLowering &TLI) {
3191 assert(!Codes.empty() && "Must have at least one constraint");
3192
3193 std::string *Current = &Codes[0];
3194 TargetLowering::ConstraintType CurType = TLI.getConstraintType(*Current);
3195 if (Codes.size() == 1) { // Single-letter constraints ('r') are very common.
3196 ConstraintCode = *Current;
3197 ConstraintType = CurType;
3198 return;
3199 }
3200
3201 unsigned CurGenerality = getConstraintGenerality(CurType);
3202
3203 // If we have multiple constraints, try to pick the most general one ahead
3204 // of time. This isn't a wonderful solution, but handles common cases.
3205 for (unsigned j = 1, e = Codes.size(); j != e; ++j) {
3206 TargetLowering::ConstraintType ThisType = TLI.getConstraintType(Codes[j]);
3207 unsigned ThisGenerality = getConstraintGenerality(ThisType);
3208 if (ThisGenerality > CurGenerality) {
3209 // This constraint letter is more general than the previous one,
3210 // use it.
3211 CurType = ThisType;
3212 Current = &Codes[j];
3213 CurGenerality = ThisGenerality;
3214 }
3215 }
3216
3217 ConstraintCode = *Current;
3218 ConstraintType = CurType;
3219}
3220
3221
3222void SelectionDAGLowering::
3223GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
3224 std::set<unsigned> &OutputRegs,
3225 std::set<unsigned> &InputRegs) {
3226 // Compute whether this value requires an input register, an output register,
3227 // or both.
3228 bool isOutReg = false;
3229 bool isInReg = false;
3230 switch (OpInfo.Type) {
3231 case InlineAsm::isOutput:
3232 isOutReg = true;
3233
3234 // If this is an early-clobber output, or if there is an input
3235 // constraint that matches this, we need to reserve the input register
3236 // so no other inputs allocate to it.
3237 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3238 break;
3239 case InlineAsm::isInput:
3240 isInReg = true;
3241 isOutReg = false;
3242 break;
3243 case InlineAsm::isClobber:
3244 isOutReg = true;
3245 isInReg = true;
3246 break;
3247 }
3248
3249
3250 MachineFunction &MF = DAG.getMachineFunction();
3251 std::vector<unsigned> Regs;
3252
3253 // If this is a constraint for a single physreg, or a constraint for a
3254 // register class, find it.
3255 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3256 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3257 OpInfo.ConstraintVT);
3258
3259 unsigned NumRegs = 1;
3260 if (OpInfo.ConstraintVT != MVT::Other)
3261 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3262 MVT::ValueType RegVT;
3263 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3264
3265
3266 // If this is a constraint for a specific physical register, like {r17},
3267 // assign it now.
3268 if (PhysReg.first) {
3269 if (OpInfo.ConstraintVT == MVT::Other)
3270 ValueVT = *PhysReg.second->vt_begin();
3271
3272 // Get the actual register value type. This is important, because the user
3273 // may have asked for (e.g.) the AX register in i32 type. We need to
3274 // remember that AX is actually i16 to get the right extension.
3275 RegVT = *PhysReg.second->vt_begin();
3276
3277 // This is a explicit reference to a physical register.
3278 Regs.push_back(PhysReg.first);
3279
3280 // If this is an expanded reference, add the rest of the regs to Regs.
3281 if (NumRegs != 1) {
3282 TargetRegisterClass::iterator I = PhysReg.second->begin();
3283 TargetRegisterClass::iterator E = PhysReg.second->end();
3284 for (; *I != PhysReg.first; ++I)
3285 assert(I != E && "Didn't find reg!");
3286
3287 // Already added the first reg.
3288 --NumRegs; ++I;
3289 for (; NumRegs; --NumRegs, ++I) {
3290 assert(I != E && "Ran out of registers to allocate!");
3291 Regs.push_back(*I);
3292 }
3293 }
3294 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3295 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3296 return;
3297 }
3298
3299 // Otherwise, if this was a reference to an LLVM register class, create vregs
3300 // for this reference.
3301 std::vector<unsigned> RegClassRegs;
3302 const TargetRegisterClass *RC = PhysReg.second;
3303 if (RC) {
3304 // If this is an early clobber or tied register, our regalloc doesn't know
3305 // how to maintain the constraint. If it isn't, go ahead and create vreg
3306 // and let the regalloc do the right thing.
3307 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3308 // If there is some other early clobber and this is an input register,
3309 // then we are forced to pre-allocate the input reg so it doesn't
3310 // conflict with the earlyclobber.
3311 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
3312 RegVT = *PhysReg.second->vt_begin();
3313
3314 if (OpInfo.ConstraintVT == MVT::Other)
3315 ValueVT = RegVT;
3316
3317 // Create the appropriate number of virtual registers.
3318 SSARegMap *RegMap = MF.getSSARegMap();
3319 for (; NumRegs; --NumRegs)
3320 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3321
3322 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3323 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3324 return;
3325 }
3326
3327 // Otherwise, we can't allocate it. Let the code below figure out how to
3328 // maintain these constraints.
3329 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3330
3331 } else {
3332 // This is a reference to a register class that doesn't directly correspond
3333 // to an LLVM register class. Allocate NumRegs consecutive, available,
3334 // registers from the class.
3335 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3336 OpInfo.ConstraintVT);
3337 }
3338
3339 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3340 unsigned NumAllocated = 0;
3341 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3342 unsigned Reg = RegClassRegs[i];
3343 // See if this register is available.
3344 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3345 (isInReg && InputRegs.count(Reg))) { // Already used.
3346 // Make sure we find consecutive registers.
3347 NumAllocated = 0;
3348 continue;
3349 }
3350
3351 // Check to see if this register is allocatable (i.e. don't give out the
3352 // stack pointer).
3353 if (RC == 0) {
3354 RC = isAllocatableRegister(Reg, MF, TLI, MRI);
3355 if (!RC) { // Couldn't allocate this register.
3356 // Reset NumAllocated to make sure we return consecutive registers.
3357 NumAllocated = 0;
3358 continue;
3359 }
3360 }
3361
3362 // Okay, this register is good, we can use it.
3363 ++NumAllocated;
3364
3365 // If we allocated enough consecutive registers, succeed.
3366 if (NumAllocated == NumRegs) {
3367 unsigned RegStart = (i-NumAllocated)+1;
3368 unsigned RegEnd = i+1;
3369 // Mark all of the allocated registers used.
3370 for (unsigned i = RegStart; i != RegEnd; ++i)
3371 Regs.push_back(RegClassRegs[i]);
3372
3373 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
3374 OpInfo.ConstraintVT);
3375 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3376 return;
3377 }
3378 }
3379
3380 // Otherwise, we couldn't allocate enough registers for this.
3381 return;
3382}
3383
3384
3385/// visitInlineAsm - Handle a call to an InlineAsm object.
3386///
3387void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3388 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
3389
3390 /// ConstraintOperands - Information about all of the constraints.
3391 std::vector<AsmOperandInfo> ConstraintOperands;
3392
3393 SDOperand Chain = getRoot();
3394 SDOperand Flag;
3395
3396 std::set<unsigned> OutputRegs, InputRegs;
3397
3398 // Do a prepass over the constraints, canonicalizing them, and building up the
3399 // ConstraintOperands list.
3400 std::vector<InlineAsm::ConstraintInfo>
3401 ConstraintInfos = IA->ParseConstraints();
3402
3403 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3404 // constraint. If so, we can't let the register allocator allocate any input
3405 // registers, because it will not know to avoid the earlyclobbered output reg.
3406 bool SawEarlyClobber = false;
3407
3408 unsigned OpNo = 1; // OpNo - The operand of the CallInst.
3409 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3410 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
3411 AsmOperandInfo &OpInfo = ConstraintOperands.back();
3412
3413 MVT::ValueType OpVT = MVT::Other;
3414
3415 // Compute the value type for each operand.
3416 switch (OpInfo.Type) {
3417 case InlineAsm::isOutput:
3418 if (!OpInfo.isIndirect) {
3419 // The return value of the call is this value. As such, there is no
3420 // corresponding argument.
3421 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3422 OpVT = TLI.getValueType(I.getType());
3423 } else {
3424 OpInfo.CallOperandVal = I.getOperand(OpNo++);
3425 }
3426 break;
3427 case InlineAsm::isInput:
3428 OpInfo.CallOperandVal = I.getOperand(OpNo++);
3429 break;
3430 case InlineAsm::isClobber:
3431 // Nothing to do.
3432 break;
3433 }
3434
3435 // If this is an input or an indirect output, process the call argument.
3436 if (OpInfo.CallOperandVal) {
3437 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3438 const Type *OpTy = OpInfo.CallOperandVal->getType();
3439 // If this is an indirect operand, the operand is a pointer to the
3440 // accessed type.
3441 if (OpInfo.isIndirect)
3442 OpTy = cast<PointerType>(OpTy)->getElementType();
3443
3444 // If OpTy is not a first-class value, it may be a struct/union that we
3445 // can tile with integers.
3446 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3447 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3448 switch (BitSize) {
3449 default: break;
3450 case 1:
3451 case 8:
3452 case 16:
3453 case 32:
3454 case 64:
3455 OpTy = IntegerType::get(BitSize);
3456 break;
3457 }
3458 }
3459
3460 OpVT = TLI.getValueType(OpTy, true);
3461 }
3462
3463 OpInfo.ConstraintVT = OpVT;
3464
3465 // Compute the constraint code and ConstraintType to use.
3466 OpInfo.ComputeConstraintToUse(TLI);
3467
3468 // Keep track of whether we see an earlyclobber.
3469 SawEarlyClobber |= OpInfo.isEarlyClobber;
3470
3471 // If this is a memory input, and if the operand is not indirect, do what we
3472 // need to to provide an address for the memory input.
3473 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3474 !OpInfo.isIndirect) {
3475 assert(OpInfo.Type == InlineAsm::isInput &&
3476 "Can only indirectify direct input operands!");
3477
3478 // Memory operands really want the address of the value. If we don't have
3479 // an indirect input, put it in the constpool if we can, otherwise spill
3480 // it to a stack slot.
3481
3482 // If the operand is a float, integer, or vector constant, spill to a
3483 // constant pool entry to get its address.
3484 Value *OpVal = OpInfo.CallOperandVal;
3485 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3486 isa<ConstantVector>(OpVal)) {
3487 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3488 TLI.getPointerTy());
3489 } else {
3490 // Otherwise, create a stack slot and emit a store to it before the
3491 // asm.
3492 const Type *Ty = OpVal->getType();
3493 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
3494 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3495 MachineFunction &MF = DAG.getMachineFunction();
3496 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3497 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3498 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3499 OpInfo.CallOperand = StackSlot;
3500 }
3501
3502 // There is no longer a Value* corresponding to this operand.
3503 OpInfo.CallOperandVal = 0;
3504 // It is now an indirect operand.
3505 OpInfo.isIndirect = true;
3506 }
3507
3508 // If this constraint is for a specific register, allocate it before
3509 // anything else.
3510 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3511 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3512 }
3513 ConstraintInfos.clear();
3514
3515
3516 // Second pass - Loop over all of the operands, assigning virtual or physregs
3517 // to registerclass operands.
3518 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3519 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3520
3521 // C_Register operands have already been allocated, Other/Memory don't need
3522 // to be.
3523 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3524 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3525 }
3526
3527 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3528 std::vector<SDOperand> AsmNodeOperands;
3529 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3530 AsmNodeOperands.push_back(
3531 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3532
3533
3534 // Loop over all of the inputs, copying the operand values into the
3535 // appropriate registers and processing the output regs.
3536 RegsForValue RetValRegs;
3537
3538 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3539 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3540
3541 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3542 AsmOperandInfo &OpInfo = ConstraintOperands[i];
3543
3544 switch (OpInfo.Type) {
3545 case InlineAsm::isOutput: {
3546 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3547 OpInfo.ConstraintType != TargetLowering::C_Register) {
3548 // Memory output, or 'other' output (e.g. 'X' constraint).
3549 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
3550
3551 // Add information to the INLINEASM node to know about this output.
3552 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3553 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3554 TLI.getPointerTy()));
3555 AsmNodeOperands.push_back(OpInfo.CallOperand);
3556 break;
3557 }
3558
3559 // Otherwise, this is a register or register class output.
3560
3561 // Copy the output from the appropriate register. Find a register that
3562 // we can use.
3563 if (OpInfo.AssignedRegs.Regs.empty()) {
3564 cerr << "Couldn't allocate output reg for contraint '"
3565 << OpInfo.ConstraintCode << "'!\n";
3566 exit(1);
3567 }
3568
3569 if (!OpInfo.isIndirect) {
3570 // This is the result value of the call.
3571 assert(RetValRegs.Regs.empty() &&
3572 "Cannot have multiple output constraints yet!");
3573 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3574 RetValRegs = OpInfo.AssignedRegs;
3575 } else {
3576 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
3577 OpInfo.CallOperandVal));
3578 }
3579
3580 // Add information to the INLINEASM node to know that this register is
3581 // set.
3582 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3583 AsmNodeOperands);
3584 break;
3585 }
3586 case InlineAsm::isInput: {
3587 SDOperand InOperandVal = OpInfo.CallOperand;
3588
3589 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
3590 // If this is required to match an output register we have already set,
3591 // just use its register.
3592 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
3593
3594 // Scan until we find the definition we already emitted of this operand.
3595 // When we find it, create a RegsForValue operand.
3596 unsigned CurOp = 2; // The first operand.
3597 for (; OperandNo; --OperandNo) {
3598 // Advance to the next operand.
3599 unsigned NumOps =
3600 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3601 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3602 (NumOps & 7) == 4 /*MEM*/) &&
3603 "Skipped past definitions?");
3604 CurOp += (NumOps>>3)+1;
3605 }
3606
3607 unsigned NumOps =
3608 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
3609 if ((NumOps & 7) == 2 /*REGDEF*/) {
3610 // Add NumOps>>3 registers to MatchedRegs.
3611 RegsForValue MatchedRegs;
3612 MatchedRegs.ValueVT = InOperandVal.getValueType();
3613 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3614 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3615 unsigned Reg =
3616 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3617 MatchedRegs.Regs.push_back(Reg);
3618 }
3619
3620 // Use the produced MatchedRegs object to
3621 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
3622 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3623 break;
3624 } else {
3625 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3626 assert(0 && "matching constraints for memory operands unimp");
3627 }
3628 }
3629
3630 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
3631 assert(!OpInfo.isIndirect &&
3632 "Don't know how to handle indirect other inputs yet!");
3633
Chris Lattnera531abc2007-08-25 00:47:38 +00003634 std::vector<SDOperand> Ops;
3635 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
3636 Ops, DAG);
3637 if (Ops.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003638 cerr << "Invalid operand for inline asm constraint '"
3639 << OpInfo.ConstraintCode << "'!\n";
3640 exit(1);
3641 }
3642
3643 // Add information to the INLINEASM node to know about this input.
Chris Lattnera531abc2007-08-25 00:47:38 +00003644 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003645 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3646 TLI.getPointerTy()));
Chris Lattnera531abc2007-08-25 00:47:38 +00003647 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003648 break;
3649 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
3650 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
3651 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3652 "Memory operands expect pointer values");
3653
3654 // Add information to the INLINEASM node to know about this input.
3655 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3656 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3657 TLI.getPointerTy()));
3658 AsmNodeOperands.push_back(InOperandVal);
3659 break;
3660 }
3661
3662 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3663 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3664 "Unknown constraint type!");
3665 assert(!OpInfo.isIndirect &&
3666 "Don't know how to handle indirect register inputs yet!");
3667
3668 // Copy the input into the appropriate registers.
3669 assert(!OpInfo.AssignedRegs.Regs.empty() &&
3670 "Couldn't allocate input reg!");
3671
3672 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
3673
3674 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
3675 AsmNodeOperands);
3676 break;
3677 }
3678 case InlineAsm::isClobber: {
3679 // Add the clobbered value to the operand list, so that the register
3680 // allocator is aware that the physreg got clobbered.
3681 if (!OpInfo.AssignedRegs.Regs.empty())
3682 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
3683 AsmNodeOperands);
3684 break;
3685 }
3686 }
3687 }
3688
3689 // Finish up input operands.
3690 AsmNodeOperands[0] = Chain;
3691 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3692
3693 Chain = DAG.getNode(ISD::INLINEASM,
3694 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
3695 &AsmNodeOperands[0], AsmNodeOperands.size());
3696 Flag = Chain.getValue(1);
3697
3698 // If this asm returns a register value, copy the result from that register
3699 // and set it as the value of the call.
3700 if (!RetValRegs.Regs.empty()) {
3701 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
3702
3703 // If the result of the inline asm is a vector, it may have the wrong
3704 // width/num elts. Make sure to convert it to the right type with
3705 // bit_convert.
3706 if (MVT::isVector(Val.getValueType())) {
3707 const VectorType *VTy = cast<VectorType>(I.getType());
3708 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
3709
3710 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
3711 }
3712
3713 setValue(&I, Val);
3714 }
3715
3716 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3717
3718 // Process indirect outputs, first output all of the flagged copies out of
3719 // physregs.
3720 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
3721 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
3722 Value *Ptr = IndirectStoresToEmit[i].second;
3723 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
3724 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
3725 }
3726
3727 // Emit the non-flagged stores from the physregs.
3728 SmallVector<SDOperand, 8> OutChains;
3729 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
3730 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
3731 getValue(StoresToEmit[i].second),
3732 StoresToEmit[i].second, 0));
3733 if (!OutChains.empty())
3734 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3735 &OutChains[0], OutChains.size());
3736 DAG.setRoot(Chain);
3737}
3738
3739
3740void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3741 SDOperand Src = getValue(I.getOperand(0));
3742
3743 MVT::ValueType IntPtr = TLI.getPointerTy();
3744
3745 if (IntPtr < Src.getValueType())
3746 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3747 else if (IntPtr > Src.getValueType())
3748 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
3749
3750 // Scale the source by the type size.
3751 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
3752 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3753 Src, getIntPtrConstant(ElementSize));
3754
3755 TargetLowering::ArgListTy Args;
3756 TargetLowering::ArgListEntry Entry;
3757 Entry.Node = Src;
3758 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3759 Args.push_back(Entry);
3760
3761 std::pair<SDOperand,SDOperand> Result =
3762 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
3763 DAG.getExternalSymbol("malloc", IntPtr),
3764 Args, DAG);
3765 setValue(&I, Result.first); // Pointers always fit in registers
3766 DAG.setRoot(Result.second);
3767}
3768
3769void SelectionDAGLowering::visitFree(FreeInst &I) {
3770 TargetLowering::ArgListTy Args;
3771 TargetLowering::ArgListEntry Entry;
3772 Entry.Node = getValue(I.getOperand(0));
3773 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3774 Args.push_back(Entry);
3775 MVT::ValueType IntPtr = TLI.getPointerTy();
3776 std::pair<SDOperand,SDOperand> Result =
3777 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
3778 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3779 DAG.setRoot(Result.second);
3780}
3781
3782// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3783// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3784// instructions are special in various ways, which require special support to
3785// insert. The specified MachineInstr is created but not inserted into any
3786// basic blocks, and the scheduler passes ownership of it to this method.
3787MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3788 MachineBasicBlock *MBB) {
3789 cerr << "If a target marks an instruction with "
3790 << "'usesCustomDAGSchedInserter', it must implement "
3791 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
3792 abort();
3793 return 0;
3794}
3795
3796void SelectionDAGLowering::visitVAStart(CallInst &I) {
3797 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3798 getValue(I.getOperand(1)),
3799 DAG.getSrcValue(I.getOperand(1))));
3800}
3801
3802void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
3803 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3804 getValue(I.getOperand(0)),
3805 DAG.getSrcValue(I.getOperand(0)));
3806 setValue(&I, V);
3807 DAG.setRoot(V.getValue(1));
3808}
3809
3810void SelectionDAGLowering::visitVAEnd(CallInst &I) {
3811 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3812 getValue(I.getOperand(1)),
3813 DAG.getSrcValue(I.getOperand(1))));
3814}
3815
3816void SelectionDAGLowering::visitVACopy(CallInst &I) {
3817 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3818 getValue(I.getOperand(1)),
3819 getValue(I.getOperand(2)),
3820 DAG.getSrcValue(I.getOperand(1)),
3821 DAG.getSrcValue(I.getOperand(2))));
3822}
3823
3824/// TargetLowering::LowerArguments - This is the default LowerArguments
3825/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
3826/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3827/// integrated into SDISel.
3828std::vector<SDOperand>
3829TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
3830 const FunctionType *FTy = F.getFunctionType();
3831 const ParamAttrsList *Attrs = FTy->getParamAttrs();
3832 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3833 std::vector<SDOperand> Ops;
3834 Ops.push_back(DAG.getRoot());
3835 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3836 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3837
3838 // Add one result value for each formal argument.
3839 std::vector<MVT::ValueType> RetVals;
3840 unsigned j = 1;
3841 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3842 I != E; ++I, ++j) {
3843 MVT::ValueType VT = getValueType(I->getType());
3844 unsigned Flags = ISD::ParamFlags::NoFlagSet;
3845 unsigned OriginalAlignment =
3846 getTargetData()->getABITypeAlignment(I->getType());
3847
3848 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3849 // that is zero extended!
3850 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
3851 Flags &= ~(ISD::ParamFlags::SExt);
3852 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
3853 Flags |= ISD::ParamFlags::SExt;
3854 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
3855 Flags |= ISD::ParamFlags::InReg;
3856 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
3857 Flags |= ISD::ParamFlags::StructReturn;
Rafael Espindolae4e4d3e2007-08-10 14:44:42 +00003858 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ByVal)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003859 Flags |= ISD::ParamFlags::ByVal;
Rafael Espindolae4e4d3e2007-08-10 14:44:42 +00003860 const PointerType *Ty = cast<PointerType>(I->getType());
3861 const StructType *STy = cast<StructType>(Ty->getElementType());
3862 unsigned StructAlign = Log2_32(getTargetData()->getABITypeAlignment(STy));
3863 unsigned StructSize = getTargetData()->getTypeSize(STy);
3864 Flags |= (StructAlign << ISD::ParamFlags::ByValAlignOffs);
3865 Flags |= (StructSize << ISD::ParamFlags::ByValSizeOffs);
3866 }
Duncan Sands38947cd2007-07-27 12:58:54 +00003867 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::Nest))
3868 Flags |= ISD::ParamFlags::Nest;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003869 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
3870
3871 switch (getTypeAction(VT)) {
3872 default: assert(0 && "Unknown type action!");
3873 case Legal:
3874 RetVals.push_back(VT);
3875 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3876 break;
3877 case Promote:
3878 RetVals.push_back(getTypeToTransformTo(VT));
3879 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3880 break;
3881 case Expand: {
3882 // If this is an illegal type, it needs to be broken up to fit into
3883 // registers.
3884 MVT::ValueType RegisterVT = getRegisterType(VT);
3885 unsigned NumRegs = getNumRegisters(VT);
3886 for (unsigned i = 0; i != NumRegs; ++i) {
3887 RetVals.push_back(RegisterVT);
3888 // if it isn't first piece, alignment must be 1
3889 if (i > 0)
3890 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3891 (1 << ISD::ParamFlags::OrigAlignmentOffs);
3892 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3893 }
3894 break;
3895 }
3896 }
3897 }
3898
3899 RetVals.push_back(MVT::Other);
3900
3901 // Create the node.
3902 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3903 DAG.getNodeValueTypes(RetVals), RetVals.size(),
3904 &Ops[0], Ops.size()).Val;
3905 unsigned NumArgRegs = Result->getNumValues() - 1;
3906 DAG.setRoot(SDOperand(Result, NumArgRegs));
3907
3908 // Set up the return result vector.
3909 Ops.clear();
3910 unsigned i = 0;
3911 unsigned Idx = 1;
3912 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3913 ++I, ++Idx) {
3914 MVT::ValueType VT = getValueType(I->getType());
3915
3916 switch (getTypeAction(VT)) {
3917 default: assert(0 && "Unknown type action!");
3918 case Legal:
3919 Ops.push_back(SDOperand(Result, i++));
3920 break;
3921 case Promote: {
3922 SDOperand Op(Result, i++);
3923 if (MVT::isInteger(VT)) {
3924 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
3925 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3926 DAG.getValueType(VT));
3927 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
3928 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3929 DAG.getValueType(VT));
3930 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3931 } else {
3932 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3933 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3934 }
3935 Ops.push_back(Op);
3936 break;
3937 }
3938 case Expand: {
3939 MVT::ValueType PartVT = getRegisterType(VT);
3940 unsigned NumParts = getNumRegisters(VT);
3941 SmallVector<SDOperand, 4> Parts(NumParts);
3942 for (unsigned j = 0; j != NumParts; ++j)
3943 Parts[j] = SDOperand(Result, i++);
3944 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT));
3945 break;
3946 }
3947 }
3948 }
3949 assert(i == NumArgRegs && "Argument register count mismatch!");
3950 return Ops;
3951}
3952
3953
3954/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3955/// implementation, which just inserts an ISD::CALL node, which is later custom
3956/// lowered by the target to something concrete. FIXME: When all targets are
3957/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3958std::pair<SDOperand, SDOperand>
3959TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3960 bool RetTyIsSigned, bool isVarArg,
3961 unsigned CallingConv, bool isTailCall,
3962 SDOperand Callee,
3963 ArgListTy &Args, SelectionDAG &DAG) {
3964 SmallVector<SDOperand, 32> Ops;
3965 Ops.push_back(Chain); // Op#0 - Chain
3966 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3967 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3968 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3969 Ops.push_back(Callee);
3970
3971 // Handle all of the outgoing arguments.
3972 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
3973 MVT::ValueType VT = getValueType(Args[i].Ty);
3974 SDOperand Op = Args[i].Node;
3975 unsigned Flags = ISD::ParamFlags::NoFlagSet;
3976 unsigned OriginalAlignment =
3977 getTargetData()->getABITypeAlignment(Args[i].Ty);
3978
3979 if (Args[i].isSExt)
3980 Flags |= ISD::ParamFlags::SExt;
3981 if (Args[i].isZExt)
3982 Flags |= ISD::ParamFlags::ZExt;
3983 if (Args[i].isInReg)
3984 Flags |= ISD::ParamFlags::InReg;
3985 if (Args[i].isSRet)
3986 Flags |= ISD::ParamFlags::StructReturn;
Rafael Espindolab8bcfcd2007-08-20 15:18:24 +00003987 if (Args[i].isByVal) {
3988 Flags |= ISD::ParamFlags::ByVal;
3989 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
3990 const StructType *STy = cast<StructType>(Ty->getElementType());
3991 unsigned StructAlign = Log2_32(getTargetData()->getABITypeAlignment(STy));
3992 unsigned StructSize = getTargetData()->getTypeSize(STy);
3993 Flags |= (StructAlign << ISD::ParamFlags::ByValAlignOffs);
3994 Flags |= (StructSize << ISD::ParamFlags::ByValSizeOffs);
3995 }
Duncan Sands38947cd2007-07-27 12:58:54 +00003996 if (Args[i].isNest)
3997 Flags |= ISD::ParamFlags::Nest;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003998 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
3999
4000 switch (getTypeAction(VT)) {
4001 default: assert(0 && "Unknown type action!");
4002 case Legal:
4003 Ops.push_back(Op);
4004 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
4005 break;
4006 case Promote:
4007 if (MVT::isInteger(VT)) {
4008 unsigned ExtOp;
4009 if (Args[i].isSExt)
4010 ExtOp = ISD::SIGN_EXTEND;
4011 else if (Args[i].isZExt)
4012 ExtOp = ISD::ZERO_EXTEND;
4013 else
4014 ExtOp = ISD::ANY_EXTEND;
4015 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
4016 } else {
4017 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
4018 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
4019 }
4020 Ops.push_back(Op);
4021 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
4022 break;
4023 case Expand: {
4024 MVT::ValueType PartVT = getRegisterType(VT);
4025 unsigned NumParts = getNumRegisters(VT);
4026 SmallVector<SDOperand, 4> Parts(NumParts);
4027 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT);
4028 for (unsigned i = 0; i != NumParts; ++i) {
4029 // if it isn't first piece, alignment must be 1
4030 unsigned MyFlags = Flags;
4031 if (i != 0)
4032 MyFlags = (MyFlags & (~ISD::ParamFlags::OrigAlignment)) |
4033 (1 << ISD::ParamFlags::OrigAlignmentOffs);
4034
4035 Ops.push_back(Parts[i]);
4036 Ops.push_back(DAG.getConstant(MyFlags, MVT::i32));
4037 }
4038 break;
4039 }
4040 }
4041 }
4042
4043 // Figure out the result value types.
4044 MVT::ValueType VT = getValueType(RetTy);
4045 MVT::ValueType RegisterVT = getRegisterType(VT);
4046 unsigned NumRegs = getNumRegisters(VT);
4047 SmallVector<MVT::ValueType, 4> RetTys(NumRegs);
4048 for (unsigned i = 0; i != NumRegs; ++i)
4049 RetTys[i] = RegisterVT;
4050
4051 RetTys.push_back(MVT::Other); // Always has a chain.
4052
4053 // Create the CALL node.
4054 SDOperand Res = DAG.getNode(ISD::CALL,
4055 DAG.getVTList(&RetTys[0], NumRegs + 1),
4056 &Ops[0], Ops.size());
Chris Lattnerbc1200c2007-08-02 18:08:16 +00004057 Chain = Res.getValue(NumRegs);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004058
4059 // Gather up the call result into a single value.
4060 if (RetTy != Type::VoidTy) {
4061 ISD::NodeType AssertOp = ISD::AssertSext;
4062 if (!RetTyIsSigned)
4063 AssertOp = ISD::AssertZext;
4064 SmallVector<SDOperand, 4> Results(NumRegs);
4065 for (unsigned i = 0; i != NumRegs; ++i)
4066 Results[i] = Res.getValue(i);
4067 Res = getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT, AssertOp);
4068 }
4069
4070 return std::make_pair(Res, Chain);
4071}
4072
4073SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4074 assert(0 && "LowerOperation not implemented for this target!");
4075 abort();
4076 return SDOperand();
4077}
4078
4079SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4080 SelectionDAG &DAG) {
4081 assert(0 && "CustomPromoteOperation not implemented for this target!");
4082 abort();
4083 return SDOperand();
4084}
4085
4086/// getMemsetValue - Vectorized representation of the memset value
4087/// operand.
4088static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
4089 SelectionDAG &DAG) {
4090 MVT::ValueType CurVT = VT;
4091 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4092 uint64_t Val = C->getValue() & 255;
4093 unsigned Shift = 8;
4094 while (CurVT != MVT::i8) {
4095 Val = (Val << Shift) | Val;
4096 Shift <<= 1;
4097 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
4098 }
4099 return DAG.getConstant(Val, VT);
4100 } else {
4101 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4102 unsigned Shift = 8;
4103 while (CurVT != MVT::i8) {
4104 Value =
4105 DAG.getNode(ISD::OR, VT,
4106 DAG.getNode(ISD::SHL, VT, Value,
4107 DAG.getConstant(Shift, MVT::i8)), Value);
4108 Shift <<= 1;
4109 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
4110 }
4111
4112 return Value;
4113 }
4114}
4115
4116/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4117/// used when a memcpy is turned into a memset when the source is a constant
4118/// string ptr.
4119static SDOperand getMemsetStringVal(MVT::ValueType VT,
4120 SelectionDAG &DAG, TargetLowering &TLI,
4121 std::string &Str, unsigned Offset) {
4122 uint64_t Val = 0;
4123 unsigned MSB = MVT::getSizeInBits(VT) / 8;
4124 if (TLI.isLittleEndian())
4125 Offset = Offset + MSB - 1;
4126 for (unsigned i = 0; i != MSB; ++i) {
4127 Val = (Val << 8) | (unsigned char)Str[Offset];
4128 Offset += TLI.isLittleEndian() ? -1 : 1;
4129 }
4130 return DAG.getConstant(Val, VT);
4131}
4132
4133/// getMemBasePlusOffset - Returns base and offset node for the
4134static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4135 SelectionDAG &DAG, TargetLowering &TLI) {
4136 MVT::ValueType VT = Base.getValueType();
4137 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4138}
4139
4140/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
4141/// to replace the memset / memcpy is below the threshold. It also returns the
4142/// types of the sequence of memory ops to perform memset / memcpy.
4143static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4144 unsigned Limit, uint64_t Size,
4145 unsigned Align, TargetLowering &TLI) {
4146 MVT::ValueType VT;
4147
4148 if (TLI.allowsUnalignedMemoryAccesses()) {
4149 VT = MVT::i64;
4150 } else {
4151 switch (Align & 7) {
4152 case 0:
4153 VT = MVT::i64;
4154 break;
4155 case 4:
4156 VT = MVT::i32;
4157 break;
4158 case 2:
4159 VT = MVT::i16;
4160 break;
4161 default:
4162 VT = MVT::i8;
4163 break;
4164 }
4165 }
4166
4167 MVT::ValueType LVT = MVT::i64;
4168 while (!TLI.isTypeLegal(LVT))
4169 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4170 assert(MVT::isInteger(LVT));
4171
4172 if (VT > LVT)
4173 VT = LVT;
4174
4175 unsigned NumMemOps = 0;
4176 while (Size != 0) {
4177 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4178 while (VTSize > Size) {
4179 VT = (MVT::ValueType)((unsigned)VT - 1);
4180 VTSize >>= 1;
4181 }
4182 assert(MVT::isInteger(VT));
4183
4184 if (++NumMemOps > Limit)
4185 return false;
4186 MemOps.push_back(VT);
4187 Size -= VTSize;
4188 }
4189
4190 return true;
4191}
4192
4193void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
4194 SDOperand Op1 = getValue(I.getOperand(1));
4195 SDOperand Op2 = getValue(I.getOperand(2));
4196 SDOperand Op3 = getValue(I.getOperand(3));
4197 SDOperand Op4 = getValue(I.getOperand(4));
4198 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4199 if (Align == 0) Align = 1;
4200
Dan Gohmancc863aa2007-08-27 16:26:13 +00004201 // If the source and destination are known to not be aliases, we can
4202 // lower memmove as memcpy.
4203 if (Op == ISD::MEMMOVE) {
4204 uint64_t Size = -1;
4205 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
4206 Size = C->getValue();
4207 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
4208 AliasAnalysis::NoAlias)
4209 Op = ISD::MEMCPY;
4210 }
4211
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004212 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4213 std::vector<MVT::ValueType> MemOps;
4214
4215 // Expand memset / memcpy to a series of load / store ops
4216 // if the size operand falls below a certain threshold.
4217 SmallVector<SDOperand, 8> OutChains;
4218 switch (Op) {
4219 default: break; // Do nothing for now.
4220 case ISD::MEMSET: {
4221 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4222 Size->getValue(), Align, TLI)) {
4223 unsigned NumMemOps = MemOps.size();
4224 unsigned Offset = 0;
4225 for (unsigned i = 0; i < NumMemOps; i++) {
4226 MVT::ValueType VT = MemOps[i];
4227 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4228 SDOperand Value = getMemsetValue(Op2, VT, DAG);
4229 SDOperand Store = DAG.getStore(getRoot(), Value,
4230 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
4231 I.getOperand(1), Offset);
4232 OutChains.push_back(Store);
4233 Offset += VTSize;
4234 }
4235 }
4236 break;
4237 }
4238 case ISD::MEMCPY: {
4239 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4240 Size->getValue(), Align, TLI)) {
4241 unsigned NumMemOps = MemOps.size();
4242 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
4243 GlobalAddressSDNode *G = NULL;
4244 std::string Str;
4245 bool CopyFromStr = false;
4246
4247 if (Op2.getOpcode() == ISD::GlobalAddress)
4248 G = cast<GlobalAddressSDNode>(Op2);
4249 else if (Op2.getOpcode() == ISD::ADD &&
4250 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4251 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4252 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
4253 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
4254 }
4255 if (G) {
4256 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
4257 if (GV && GV->isConstant()) {
4258 Str = GV->getStringValue(false);
4259 if (!Str.empty()) {
4260 CopyFromStr = true;
4261 SrcOff += SrcDelta;
4262 }
4263 }
4264 }
4265
4266 for (unsigned i = 0; i < NumMemOps; i++) {
4267 MVT::ValueType VT = MemOps[i];
4268 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
4269 SDOperand Value, Chain, Store;
4270
4271 if (CopyFromStr) {
4272 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4273 Chain = getRoot();
4274 Store =
4275 DAG.getStore(Chain, Value,
4276 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
4277 I.getOperand(1), DstOff);
4278 } else {
4279 Value = DAG.getLoad(VT, getRoot(),
4280 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
4281 I.getOperand(2), SrcOff);
4282 Chain = Value.getValue(1);
4283 Store =
4284 DAG.getStore(Chain, Value,
4285 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
4286 I.getOperand(1), DstOff);
4287 }
4288 OutChains.push_back(Store);
4289 SrcOff += VTSize;
4290 DstOff += VTSize;
4291 }
4292 }
4293 break;
4294 }
4295 }
4296
4297 if (!OutChains.empty()) {
4298 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4299 &OutChains[0], OutChains.size()));
4300 return;
4301 }
4302 }
4303
4304 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
4305}
4306
4307//===----------------------------------------------------------------------===//
4308// SelectionDAGISel code
4309//===----------------------------------------------------------------------===//
4310
4311unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4312 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4313}
4314
4315void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4316 AU.addRequired<AliasAnalysis>();
4317 AU.setPreservesAll();
4318}
4319
4320
4321
4322bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohmancc863aa2007-08-27 16:26:13 +00004323 // Get alias analysis for load/store combining.
4324 AA = &getAnalysis<AliasAnalysis>();
4325
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004326 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4327 RegMap = MF.getSSARegMap();
4328 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4329
4330 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4331
4332 if (ExceptionHandling)
4333 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4334 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4335 // Mark landing pad.
4336 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
4337
4338 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4339 SelectBasicBlock(I, MF, FuncInfo);
4340
4341 // Add function live-ins to entry block live-in set.
4342 BasicBlock *EntryBB = &Fn.getEntryBlock();
4343 BB = FuncInfo.MBBMap[EntryBB];
4344 if (!MF.livein_empty())
4345 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4346 E = MF.livein_end(); I != E; ++I)
4347 BB->addLiveIn(I->first);
4348
4349#ifndef NDEBUG
4350 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4351 "Not all catch info was assigned to a landing pad!");
4352#endif
4353
4354 return true;
4355}
4356
4357SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4358 unsigned Reg) {
4359 SDOperand Op = getValue(V);
4360 assert((Op.getOpcode() != ISD::CopyFromReg ||
4361 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4362 "Copy from a reg to the same reg!");
4363
4364 MVT::ValueType SrcVT = Op.getValueType();
4365 MVT::ValueType RegisterVT = TLI.getRegisterType(SrcVT);
4366 unsigned NumRegs = TLI.getNumRegisters(SrcVT);
4367 SmallVector<SDOperand, 8> Regs(NumRegs);
4368 SmallVector<SDOperand, 8> Chains(NumRegs);
4369
4370 // Copy the value by legal parts into sequential virtual registers.
4371 getCopyToParts(DAG, Op, &Regs[0], NumRegs, RegisterVT);
4372 for (unsigned i = 0; i != NumRegs; ++i)
4373 Chains[i] = DAG.getCopyToReg(getRoot(), Reg + i, Regs[i]);
4374 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4375}
4376
4377void SelectionDAGISel::
4378LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
4379 std::vector<SDOperand> &UnorderedChains) {
4380 // If this is the entry block, emit arguments.
4381 Function &F = *LLVMBB->getParent();
4382 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4383 SDOperand OldRoot = SDL.DAG.getRoot();
4384 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
4385
4386 unsigned a = 0;
4387 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4388 AI != E; ++AI, ++a)
4389 if (!AI->use_empty()) {
4390 SDL.setValue(AI, Args[a]);
4391
4392 // If this argument is live outside of the entry block, insert a copy from
4393 // whereever we got it to the vreg that other BB's will reference it as.
4394 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4395 if (VMI != FuncInfo.ValueMap.end()) {
4396 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
4397 UnorderedChains.push_back(Copy);
4398 }
4399 }
4400
4401 // Finally, if the target has anything special to do, allow it to do so.
4402 // FIXME: this should insert code into the DAG!
4403 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4404}
4405
4406static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4407 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4408 assert(!FLI.MBBMap[SrcBB]->isLandingPad() &&
4409 "Copying catch info out of a landing pad!");
4410 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4411 if (isSelector(I)) {
4412 // Apply the catch info to DestBB.
4413 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4414#ifndef NDEBUG
4415 FLI.CatchInfoFound.insert(I);
4416#endif
4417 }
4418}
4419
4420void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4421 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
4422 FunctionLoweringInfo &FuncInfo) {
Dan Gohmancc863aa2007-08-27 16:26:13 +00004423 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004424
4425 std::vector<SDOperand> UnorderedChains;
4426
4427 // Lower any arguments needed in this block if this is the entry block.
4428 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
4429 LowerArguments(LLVMBB, SDL, UnorderedChains);
4430
4431 BB = FuncInfo.MBBMap[LLVMBB];
4432 SDL.setCurrentBasicBlock(BB);
4433
4434 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4435
4436 if (ExceptionHandling && MMI && BB->isLandingPad()) {
4437 // Add a label to mark the beginning of the landing pad. Deletion of the
4438 // landing pad can thus be detected via the MachineModuleInfo.
4439 unsigned LabelID = MMI->addLandingPad(BB);
4440 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
4441 DAG.getConstant(LabelID, MVT::i32)));
4442
4443 // Mark exception register as live in.
4444 unsigned Reg = TLI.getExceptionAddressRegister();
4445 if (Reg) BB->addLiveIn(Reg);
4446
4447 // Mark exception selector register as live in.
4448 Reg = TLI.getExceptionSelectorRegister();
4449 if (Reg) BB->addLiveIn(Reg);
4450
4451 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4452 // function and list of typeids logically belong to the invoke (or, if you
4453 // like, the basic block containing the invoke), and need to be associated
4454 // with it in the dwarf exception handling tables. Currently however the
4455 // information is provided by an intrinsic (eh.selector) that can be moved
4456 // to unexpected places by the optimizers: if the unwind edge is critical,
4457 // then breaking it can result in the intrinsics being in the successor of
4458 // the landing pad, not the landing pad itself. This results in exceptions
4459 // not being caught because no typeids are associated with the invoke.
4460 // This may not be the only way things can go wrong, but it is the only way
4461 // we try to work around for the moment.
4462 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4463
4464 if (Br && Br->isUnconditional()) { // Critical edge?
4465 BasicBlock::iterator I, E;
4466 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
4467 if (isSelector(I))
4468 break;
4469
4470 if (I == E)
4471 // No catch info found - try to extract some from the successor.
4472 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
4473 }
4474 }
4475
4476 // Lower all of the non-terminator instructions.
4477 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4478 I != E; ++I)
4479 SDL.visit(*I);
4480
4481 // Ensure that all instructions which are used outside of their defining
4482 // blocks are available as virtual registers. Invoke is handled elsewhere.
4483 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
4484 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
4485 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
4486 if (VMI != FuncInfo.ValueMap.end())
4487 UnorderedChains.push_back(
4488 SDL.CopyValueToVirtualRegister(I, VMI->second));
4489 }
4490
4491 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4492 // ensure constants are generated when needed. Remember the virtual registers
4493 // that need to be added to the Machine PHI nodes as input. We cannot just
4494 // directly add them, because expansion might result in multiple MBB's for one
4495 // BB. As such, the start of the BB might correspond to a different MBB than
4496 // the end.
4497 //
4498 TerminatorInst *TI = LLVMBB->getTerminator();
4499
4500 // Emit constants only once even if used by multiple PHI nodes.
4501 std::map<Constant*, unsigned> ConstantsOut;
4502
4503 // Vector bool would be better, but vector<bool> is really slow.
4504 std::vector<unsigned char> SuccsHandled;
4505 if (TI->getNumSuccessors())
4506 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4507
4508 // Check successor nodes' PHI nodes that expect a constant to be available
4509 // from this block.
4510 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4511 BasicBlock *SuccBB = TI->getSuccessor(succ);
4512 if (!isa<PHINode>(SuccBB->begin())) continue;
4513 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4514
4515 // If this terminator has multiple identical successors (common for
4516 // switches), only handle each succ once.
4517 unsigned SuccMBBNo = SuccMBB->getNumber();
4518 if (SuccsHandled[SuccMBBNo]) continue;
4519 SuccsHandled[SuccMBBNo] = true;
4520
4521 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4522 PHINode *PN;
4523
4524 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4525 // nodes and Machine PHI nodes, but the incoming operands have not been
4526 // emitted yet.
4527 for (BasicBlock::iterator I = SuccBB->begin();
4528 (PN = dyn_cast<PHINode>(I)); ++I) {
4529 // Ignore dead phi's.
4530 if (PN->use_empty()) continue;
4531
4532 unsigned Reg;
4533 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4534
4535 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4536 unsigned &RegOut = ConstantsOut[C];
4537 if (RegOut == 0) {
4538 RegOut = FuncInfo.CreateRegForValue(C);
4539 UnorderedChains.push_back(
4540 SDL.CopyValueToVirtualRegister(C, RegOut));
4541 }
4542 Reg = RegOut;
4543 } else {
4544 Reg = FuncInfo.ValueMap[PHIOp];
4545 if (Reg == 0) {
4546 assert(isa<AllocaInst>(PHIOp) &&
4547 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4548 "Didn't codegen value into a register!??");
4549 Reg = FuncInfo.CreateRegForValue(PHIOp);
4550 UnorderedChains.push_back(
4551 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
4552 }
4553 }
4554
4555 // Remember that this register needs to added to the machine PHI node as
4556 // the input for this MBB.
4557 MVT::ValueType VT = TLI.getValueType(PN->getType());
4558 unsigned NumRegisters = TLI.getNumRegisters(VT);
4559 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
4560 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4561 }
4562 }
4563 ConstantsOut.clear();
4564
4565 // Turn all of the unordered chains into one factored node.
4566 if (!UnorderedChains.empty()) {
4567 SDOperand Root = SDL.getRoot();
4568 if (Root.getOpcode() != ISD::EntryToken) {
4569 unsigned i = 0, e = UnorderedChains.size();
4570 for (; i != e; ++i) {
4571 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4572 if (UnorderedChains[i].Val->getOperand(0) == Root)
4573 break; // Don't add the root if we already indirectly depend on it.
4574 }
4575
4576 if (i == e)
4577 UnorderedChains.push_back(Root);
4578 }
4579 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4580 &UnorderedChains[0], UnorderedChains.size()));
4581 }
4582
4583 // Lower the terminator after the copies are emitted.
4584 SDL.visit(*LLVMBB->getTerminator());
4585
4586 // Copy over any CaseBlock records that may now exist due to SwitchInst
4587 // lowering, as well as any jump table information.
4588 SwitchCases.clear();
4589 SwitchCases = SDL.SwitchCases;
4590 JTCases.clear();
4591 JTCases = SDL.JTCases;
4592 BitTestCases.clear();
4593 BitTestCases = SDL.BitTestCases;
4594
4595 // Make sure the root of the DAG is up-to-date.
4596 DAG.setRoot(SDL.getRoot());
4597}
4598
4599void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004600 // Run the DAG combiner in pre-legalize mode.
Dan Gohmancc863aa2007-08-27 16:26:13 +00004601 DAG.Combine(false, *AA);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004602
4603 DOUT << "Lowered selection DAG:\n";
4604 DEBUG(DAG.dump());
4605
4606 // Second step, hack on the DAG until it only uses operations and types that
4607 // the target supports.
4608 DAG.Legalize();
4609
4610 DOUT << "Legalized selection DAG:\n";
4611 DEBUG(DAG.dump());
4612
4613 // Run the DAG combiner in post-legalize mode.
Dan Gohmancc863aa2007-08-27 16:26:13 +00004614 DAG.Combine(true, *AA);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004615
4616 if (ViewISelDAGs) DAG.viewGraph();
4617
4618 // Third, instruction select all of the operations to machine code, adding the
4619 // code to the MachineBasicBlock.
4620 InstructionSelectBasicBlock(DAG);
4621
4622 DOUT << "Selected machine code:\n";
4623 DEBUG(BB->dump());
4624}
4625
4626void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4627 FunctionLoweringInfo &FuncInfo) {
4628 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4629 {
4630 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4631 CurDAG = &DAG;
4632
4633 // First step, lower LLVM code to some DAG. This DAG may use operations and
4634 // types that are not supported by the target.
4635 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4636
4637 // Second step, emit the lowered DAG as machine code.
4638 CodeGenAndEmitDAG(DAG);
4639 }
4640
4641 DOUT << "Total amount of phi nodes to update: "
4642 << PHINodesToUpdate.size() << "\n";
4643 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4644 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4645 << ", " << PHINodesToUpdate[i].second << ")\n";);
4646
4647 // Next, now that we know what the last MBB the LLVM BB expanded is, update
4648 // PHI nodes in successors.
4649 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
4650 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4651 MachineInstr *PHI = PHINodesToUpdate[i].first;
4652 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4653 "This is not a machine PHI node that we are updating!");
4654 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4655 PHI->addMachineBasicBlockOperand(BB);
4656 }
4657 return;
4658 }
4659
4660 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4661 // Lower header first, if it wasn't already lowered
4662 if (!BitTestCases[i].Emitted) {
4663 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4664 CurDAG = &HSDAG;
Dan Gohmancc863aa2007-08-27 16:26:13 +00004665 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004666 // Set the current basic block to the mbb we wish to insert the code into
4667 BB = BitTestCases[i].Parent;
4668 HSDL.setCurrentBasicBlock(BB);
4669 // Emit the code
4670 HSDL.visitBitTestHeader(BitTestCases[i]);
4671 HSDAG.setRoot(HSDL.getRoot());
4672 CodeGenAndEmitDAG(HSDAG);
4673 }
4674
4675 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4676 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4677 CurDAG = &BSDAG;
Dan Gohmancc863aa2007-08-27 16:26:13 +00004678 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004679 // Set the current basic block to the mbb we wish to insert the code into
4680 BB = BitTestCases[i].Cases[j].ThisBB;
4681 BSDL.setCurrentBasicBlock(BB);
4682 // Emit the code
4683 if (j+1 != ej)
4684 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4685 BitTestCases[i].Reg,
4686 BitTestCases[i].Cases[j]);
4687 else
4688 BSDL.visitBitTestCase(BitTestCases[i].Default,
4689 BitTestCases[i].Reg,
4690 BitTestCases[i].Cases[j]);
4691
4692
4693 BSDAG.setRoot(BSDL.getRoot());
4694 CodeGenAndEmitDAG(BSDAG);
4695 }
4696
4697 // Update PHI Nodes
4698 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4699 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4700 MachineBasicBlock *PHIBB = PHI->getParent();
4701 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4702 "This is not a machine PHI node that we are updating!");
4703 // This is "default" BB. We have two jumps to it. From "header" BB and
4704 // from last "case" BB.
4705 if (PHIBB == BitTestCases[i].Default) {
4706 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4707 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
4708 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4709 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4710 }
4711 // One of "cases" BB.
4712 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4713 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4714 if (cBB->succ_end() !=
4715 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4716 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4717 PHI->addMachineBasicBlockOperand(cBB);
4718 }
4719 }
4720 }
4721 }
4722
4723 // If the JumpTable record is filled in, then we need to emit a jump table.
4724 // Updating the PHI nodes is tricky in this case, since we need to determine
4725 // whether the PHI is a successor of the range check MBB or the jump table MBB
4726 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4727 // Lower header first, if it wasn't already lowered
4728 if (!JTCases[i].first.Emitted) {
4729 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4730 CurDAG = &HSDAG;
Dan Gohmancc863aa2007-08-27 16:26:13 +00004731 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004732 // Set the current basic block to the mbb we wish to insert the code into
4733 BB = JTCases[i].first.HeaderBB;
4734 HSDL.setCurrentBasicBlock(BB);
4735 // Emit the code
4736 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4737 HSDAG.setRoot(HSDL.getRoot());
4738 CodeGenAndEmitDAG(HSDAG);
4739 }
4740
4741 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4742 CurDAG = &JSDAG;
Dan Gohmancc863aa2007-08-27 16:26:13 +00004743 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004744 // Set the current basic block to the mbb we wish to insert the code into
4745 BB = JTCases[i].second.MBB;
4746 JSDL.setCurrentBasicBlock(BB);
4747 // Emit the code
4748 JSDL.visitJumpTable(JTCases[i].second);
4749 JSDAG.setRoot(JSDL.getRoot());
4750 CodeGenAndEmitDAG(JSDAG);
4751
4752 // Update PHI Nodes
4753 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4754 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4755 MachineBasicBlock *PHIBB = PHI->getParent();
4756 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4757 "This is not a machine PHI node that we are updating!");
4758 // "default" BB. We can go there only from header BB.
4759 if (PHIBB == JTCases[i].second.Default) {
4760 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4761 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
4762 }
4763 // JT BB. Just iterate over successors here
4764 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4765 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4766 PHI->addMachineBasicBlockOperand(BB);
4767 }
4768 }
4769 }
4770
4771 // If the switch block involved a branch to one of the actual successors, we
4772 // need to update PHI nodes in that block.
4773 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4774 MachineInstr *PHI = PHINodesToUpdate[i].first;
4775 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4776 "This is not a machine PHI node that we are updating!");
4777 if (BB->isSuccessor(PHI->getParent())) {
4778 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4779 PHI->addMachineBasicBlockOperand(BB);
4780 }
4781 }
4782
4783 // If we generated any switch lowering information, build and codegen any
4784 // additional DAGs necessary.
4785 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4786 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4787 CurDAG = &SDAG;
Dan Gohmancc863aa2007-08-27 16:26:13 +00004788 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004789
4790 // Set the current basic block to the mbb we wish to insert the code into
4791 BB = SwitchCases[i].ThisBB;
4792 SDL.setCurrentBasicBlock(BB);
4793
4794 // Emit the code
4795 SDL.visitSwitchCase(SwitchCases[i]);
4796 SDAG.setRoot(SDL.getRoot());
4797 CodeGenAndEmitDAG(SDAG);
4798
4799 // Handle any PHI nodes in successors of this chunk, as if we were coming
4800 // from the original BB before switch expansion. Note that PHI nodes can
4801 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4802 // handle them the right number of times.
4803 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
4804 for (MachineBasicBlock::iterator Phi = BB->begin();
4805 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4806 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4807 for (unsigned pn = 0; ; ++pn) {
4808 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4809 if (PHINodesToUpdate[pn].first == Phi) {
4810 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4811 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4812 break;
4813 }
4814 }
4815 }
4816
4817 // Don't process RHS if same block as LHS.
4818 if (BB == SwitchCases[i].FalseBB)
4819 SwitchCases[i].FalseBB = 0;
4820
4821 // If we haven't handled the RHS, do so now. Otherwise, we're done.
4822 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
4823 SwitchCases[i].FalseBB = 0;
4824 }
4825 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
4826 }
4827}
4828
4829
4830//===----------------------------------------------------------------------===//
4831/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4832/// target node in the graph.
4833void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4834 if (ViewSchedDAGs) DAG.viewGraph();
4835
4836 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
4837
4838 if (!Ctor) {
4839 Ctor = ISHeuristic;
4840 RegisterScheduler::setDefault(Ctor);
4841 }
4842
4843 ScheduleDAG *SL = Ctor(this, &DAG, BB);
4844 BB = SL->Run();
4845 delete SL;
4846}
4847
4848
4849HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4850 return new HazardRecognizer();
4851}
4852
4853//===----------------------------------------------------------------------===//
4854// Helper functions used by the generated instruction selector.
4855//===----------------------------------------------------------------------===//
4856// Calls to these methods are generated by tblgen.
4857
4858/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4859/// the dag combiner simplified the 255, we still want to match. RHS is the
4860/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4861/// specified in the .td file (e.g. 255).
4862bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmand6098272007-07-24 23:00:27 +00004863 int64_t DesiredMaskS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004864 uint64_t ActualMask = RHS->getValue();
4865 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4866
4867 // If the actual mask exactly matches, success!
4868 if (ActualMask == DesiredMask)
4869 return true;
4870
4871 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4872 if (ActualMask & ~DesiredMask)
4873 return false;
4874
4875 // Otherwise, the DAG Combiner may have proven that the value coming in is
4876 // either already zero or is not demanded. Check for known zero input bits.
4877 uint64_t NeededMask = DesiredMask & ~ActualMask;
4878 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
4879 return true;
4880
4881 // TODO: check to see if missing bits are just not demanded.
4882
4883 // Otherwise, this pattern doesn't match.
4884 return false;
4885}
4886
4887/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4888/// the dag combiner simplified the 255, we still want to match. RHS is the
4889/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4890/// specified in the .td file (e.g. 255).
4891bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmand6098272007-07-24 23:00:27 +00004892 int64_t DesiredMaskS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004893 uint64_t ActualMask = RHS->getValue();
4894 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4895
4896 // If the actual mask exactly matches, success!
4897 if (ActualMask == DesiredMask)
4898 return true;
4899
4900 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4901 if (ActualMask & ~DesiredMask)
4902 return false;
4903
4904 // Otherwise, the DAG Combiner may have proven that the value coming in is
4905 // either already zero or is not demanded. Check for known zero input bits.
4906 uint64_t NeededMask = DesiredMask & ~ActualMask;
4907
4908 uint64_t KnownZero, KnownOne;
4909 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4910
4911 // If all the missing bits in the or are already known to be set, match!
4912 if ((NeededMask & KnownOne) == NeededMask)
4913 return true;
4914
4915 // TODO: check to see if missing bits are just not demanded.
4916
4917 // Otherwise, this pattern doesn't match.
4918 return false;
4919}
4920
4921
4922/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4923/// by tblgen. Others should not call it.
4924void SelectionDAGISel::
4925SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4926 std::vector<SDOperand> InOps;
4927 std::swap(InOps, Ops);
4928
4929 Ops.push_back(InOps[0]); // input chain.
4930 Ops.push_back(InOps[1]); // input asm string.
4931
4932 unsigned i = 2, e = InOps.size();
4933 if (InOps[e-1].getValueType() == MVT::Flag)
4934 --e; // Don't process a flag operand if it is here.
4935
4936 while (i != e) {
4937 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4938 if ((Flags & 7) != 4 /*MEM*/) {
4939 // Just skip over this operand, copying the operands verbatim.
4940 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4941 i += (Flags >> 3) + 1;
4942 } else {
4943 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4944 // Otherwise, this is a memory operand. Ask the target to select it.
4945 std::vector<SDOperand> SelOps;
4946 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4947 cerr << "Could not match memory address. Inline asm failure!\n";
4948 exit(1);
4949 }
4950
4951 // Add this to the output node.
4952 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4953 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4954 IntPtrTy));
4955 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4956 i += 2;
4957 }
4958 }
4959
4960 // Add the flag input back if present.
4961 if (e != InOps.size())
4962 Ops.push_back(InOps.back());
4963}
4964
4965char SelectionDAGISel::ID = 0;