blob: 92e34bbc48f88cd96d92a0c5f2a4397a754f3bbb [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-01-07 07:47:53 +00003// 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.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Anton Korobeynikov915e6172007-04-04 21:14:49 +000015#include "llvm/ADT/BitVector.h"
Jim Laskeydcb2b832006-10-16 20:52:31 +000016#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000017#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000018#include "llvm/CodeGen/ScheduleDAG.h"
Anton Korobeynikov915e6172007-04-04 21:14:49 +000019#include "llvm/Constants.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000020#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000021#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000023#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000024#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000025#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000027#include "llvm/IntrinsicInst.h"
Reid Spencer71b79e32007-04-09 06:17:21 +000028#include "llvm/ParameterAttributes.h"
Jim Laskeyc56315c2007-01-26 21:22:28 +000029#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000032#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000034#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000035#include "llvm/CodeGen/SelectionDAG.h"
36#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000037#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000038#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"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000043#include "llvm/Target/TargetOptions.h"
Chris Lattner43535a12005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Jeff Cohen83c22e02006-02-24 02:52:40 +000047#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000048using namespace llvm;
49
Chris Lattner975f5c92005-09-01 18:44:10 +000050#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000051static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000052ViewISelDAGs("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"));
Chris Lattnere05a4612005-01-12 03:41:21 +000057#else
Chris Lattneref598052006-04-02 03:07:27 +000058static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000059#endif
60
Jim Laskey29e635d2006-08-02 12:30:23 +000061//===---------------------------------------------------------------------===//
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//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000073namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000074 cl::opt<RegisterScheduler::FunctionPassCtor, false,
75 RegisterPassParser<RegisterScheduler> >
Dale Johannesen2182f062007-07-13 17:13:54 +000076 ISHeuristic("pre-RA-sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000077 cl::init(&createDefaultScheduler),
Dale Johannesen2182f062007-07-13 17:13:54 +000078 cl::desc("Instruction schedulers available (before register allocation):"));
Jim Laskey95eda5b2006-08-01 14:21:23 +000079
Jim Laskey03593f72006-08-01 18:29:48 +000080 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000081 defaultListDAGScheduler("default", " Best scheduler for the target",
82 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000083} // namespace
84
Chris Lattner4333f8b2007-04-30 17:29:31 +000085namespace { struct AsmOperandInfo; }
86
Chris Lattner6f87d182006-02-22 22:37:12 +000087namespace {
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.
Chris Lattner996795b2006-06-28 23:17:24 +000092 struct VISIBILITY_HIDDEN RegsForValue {
Dan Gohman78677932007-06-28 23:29:44 +000093 /// Regs - This list holds the register (for legal and promoted values)
Chris Lattner6f87d182006-02-22 22:37:12 +000094 /// 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.
Dan Gohman78677932007-06-28 23:29:44 +0000120 /// If the Flag pointer is NULL, no flag is used.
Chris Lattner6f87d182006-02-22 22:37:12 +0000121 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Dan Gohman78677932007-06-28 23:29:44 +0000122 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000123
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.
Dan Gohman78677932007-06-28 23:29:44 +0000127 /// If the Flag pointer is NULL, no flag is used.
Chris Lattner571d9642006-02-23 19:21:04 +0000128 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohman78677932007-06-28 23:29:44 +0000129 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000130
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,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000135 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000136 };
137}
Evan Chengc1e1d972006-01-23 07:01:07 +0000138
Chris Lattner7a60d912005-01-07 07:47:53 +0000139namespace llvm {
140 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000141 /// 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 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000159 /// FunctionLoweringInfo - This contains information that is global to a
160 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000161 class FunctionLoweringInfo {
162 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000163 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.
Chris Lattner289aa442007-02-04 01:35:11 +0000176 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000177
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
Duncan Sands92bf2c62007-06-15 19:04:19 +0000183#ifndef NDEBUG
184 SmallSet<Instruction*, 8> CatchInfoLost;
185 SmallSet<Instruction*, 8> CatchInfoFound;
186#endif
187
Chris Lattner7a60d912005-01-07 07:47:53 +0000188 unsigned MakeReg(MVT::ValueType VT) {
189 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
190 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000191
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 }
Misha Brukman835702a2005-04-21 22:36:52 +0000197
Chris Lattner49409cb2006-03-16 19:51:18 +0000198 unsigned CreateRegForValue(const Value *V);
199
Chris Lattner7a60d912005-01-07 07:47:53 +0000200 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
Duncan Sandsfe806382007-07-04 20:52:51 +0000208/// isSelector - Return true if this instruction is a call to the
209/// eh.selector intrinsic.
210static bool isSelector(Instruction *I) {
Duncan Sands92bf2c62007-06-15 19:04:19 +0000211 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Duncan Sandsfe806382007-07-04 20:52:51 +0000212 return II->getIntrinsicID() == Intrinsic::eh_selector;
Duncan Sands92bf2c62007-06-15 19:04:19 +0000213 return false;
214}
215
Chris Lattner7a60d912005-01-07 07:47:53 +0000216/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000217/// 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.
Chris Lattner7a60d912005-01-07 07:47:53 +0000219static 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)
Nate Begemaned728c12006-03-27 01:32:24 +0000223 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000224 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000225 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000226 return true;
227 return false;
228}
229
Chris Lattner6871b232005-10-30 19:42:35 +0000230/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000231/// entry block, return true. This includes arguments used by switches, since
232/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000233static 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)
Nate Begemaned728c12006-03-27 01:32:24 +0000236 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000237 return false; // Use not in entry block.
238 return true;
239}
240
Chris Lattner7a60d912005-01-07 07:47:53 +0000241FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000242 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000243 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
244
Chris Lattner6871b232005-10-30 19:42:35 +0000245 // 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
Chris Lattner7a60d912005-01-07 07:47:53 +0000252 // 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.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000255 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000256 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
257 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000258 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000259 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000260 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000261 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +0000262 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000263 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000264
Reid Spencere0fc4df2006-10-20 07:07:24 +0000265 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000266 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000267 StaticAllocaMap[AI] =
Chris Lattnercb0ed0c2007-04-25 04:08:28 +0000268 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000269 }
270
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000271 for (; BB != EB; ++BB)
272 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000273 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.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000281 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000282 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;
Chris Lattner84a03502006-10-27 23:50:33 +0000289 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());
Dan Gohmana8665142007-06-25 16:23:39 +0000293 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner84a03502006-10-27 23:50:33 +0000294 unsigned PHIReg = ValueMap[PN];
295 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Cheng20350c42006-11-27 23:37:22 +0000296 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohman04deef32007-06-21 14:42:22 +0000297 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Cheng20350c42006-11-27 23:37:22 +0000298 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner84a03502006-10-27 23:50:33 +0000299 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000300 }
301}
302
Chris Lattner49409cb2006-03-16 19:51:18 +0000303/// 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
Dan Gohman78677932007-06-28 23:29:44 +0000309 unsigned NumRegisters = TLI.getNumRegisters(VT);
310 MVT::ValueType RegisterVT = TLI.getRegisterType(VT);
Bill Wendling47917b62007-04-24 21:13:23 +0000311
Dan Gohman7139a482007-06-27 14:34:07 +0000312 unsigned R = MakeReg(RegisterVT);
313 for (unsigned i = 1; i != NumRegisters; ++i)
314 MakeReg(RegisterVT);
315
Chris Lattner49409cb2006-03-16 19:51:18 +0000316 return R;
317}
Chris Lattner7a60d912005-01-07 07:47:53 +0000318
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
Chris Lattner79084302007-02-04 01:31:47 +0000328 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000329
Chris Lattner4d9651c2005-01-17 22:19:26 +0000330 /// 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
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000336 /// 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
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000353 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
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000362 typedef std::vector<Case> CaseVector;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000363 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000364 typedef CaseVector::iterator CaseItr;
365 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemaned728c12006-03-27 01:32:24 +0000366
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 };
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000383
384 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000385
386 /// The comparison function for sorting the switch case values in the vector.
387 /// WARNING: Case ranges should be disjoint!
Nate Begemaned728c12006-03-27 01:32:24 +0000388 struct CaseCmp {
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000389 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000390 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());
Nate Begemaned728c12006-03-27 01:32:24 +0000394 }
395 };
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000396
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000397 struct CaseBitsCmp {
398 bool operator () (const CaseBits& C1, const CaseBits& C2) {
399 return C1.Bits > C2.Bits;
400 }
401 };
402
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000403 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemaned728c12006-03-27 01:32:24 +0000404
Chris Lattner7a60d912005-01-07 07:47:53 +0000405public:
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;
Owen Anderson20a631f2006-05-03 01:29:57 +0000411 const TargetData *TD;
Dan Gohman8dc0b932007-08-27 16:26:13 +0000412 AliasAnalysis &AA;
Chris Lattner7a60d912005-01-07 07:47:53 +0000413
Nate Begemaned728c12006-03-27 01:32:24 +0000414 /// SwitchCases - Vector of CaseBlock structures used to communicate
415 /// SwitchInst code generation information.
416 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +0000417 /// JTCases - Vector of JumpTable structures used to communicate
418 /// SwitchInst code generation information.
419 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000420 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemaned728c12006-03-27 01:32:24 +0000421
Chris Lattner7a60d912005-01-07 07:47:53 +0000422 /// FuncInfo - Information about the function as a whole.
423 ///
424 FunctionLoweringInfo &FuncInfo;
425
426 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman8dc0b932007-08-27 16:26:13 +0000427 AliasAnalysis &aa,
Misha Brukman835702a2005-04-21 22:36:52 +0000428 FunctionLoweringInfo &funcinfo)
Dan Gohman8dc0b932007-08-27 16:26:13 +0000429 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Anton Korobeynikov70378262007-03-25 15:07:15 +0000430 FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000431 }
432
Chris Lattner4108bb02005-01-17 19:43:36 +0000433 /// getRoot - Return the current virtual root of the Selection DAG.
434 ///
435 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000436 if (PendingLoads.empty())
437 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000438
Chris Lattner4d9651c2005-01-17 22:19:26 +0000439 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.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000447 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
448 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000449 PendingLoads.clear();
450 DAG.setRoot(Root);
451 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000452 }
453
Chris Lattnered0110b2006-10-27 21:36:01 +0000454 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
455
Chris Lattner7a60d912005-01-07 07:47:53 +0000456 void visit(Instruction &I) { visit(I.getOpcode(), I); }
457
458 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000459 // Note: this doesn't use InstVisitor, because it has to work with
460 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000461 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
Chris Lattner4024c002006-03-15 22:19:46 +0000473 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000474 const Value *SV, SDOperand Root,
Christopher Lamb8af6d582007-04-22 23:15:30 +0000475 bool isVolatile, unsigned Alignment);
Chris Lattner7a60d912005-01-07 07:47:53 +0000476
477 SDOperand getIntPtrConstant(uint64_t Val) {
478 return DAG.getConstant(Val, TLI.getPointerTy());
479 }
480
Chris Lattner8471b152006-03-16 19:57:50 +0000481 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000482
Chris Lattner79084302007-02-04 01:31:47 +0000483 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000484 SDOperand &N = NodeMap[V];
485 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner79084302007-02-04 01:31:47 +0000486 N = NewN;
Chris Lattner7a60d912005-01-07 07:47:53 +0000487 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000488
Chris Lattner8cfd33b2007-04-30 21:11:17 +0000489 void GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
490 std::set<unsigned> &OutputRegs,
491 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000492
Chris Lattnered0110b2006-10-27 21:36:01 +0000493 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
494 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
495 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000496 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000497 void ExportFromCurrentBlock(Value *V);
Jim Laskey31fef782007-02-23 21:45:01 +0000498 void LowerCallTo(Instruction &I,
499 const Type *CalledValueTy, unsigned CallingConv,
Anton Korobeynikov3b327822007-05-23 11:08:31 +0000500 bool IsTailCall, SDOperand Callee, unsigned OpIdx,
501 MachineBasicBlock *LandingPad = NULL);
502
Chris Lattner7a60d912005-01-07 07:47:53 +0000503 // Terminator instructions.
504 void visitRet(ReturnInst &I);
505 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000506 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000507 void visitUnreachable(UnreachableInst &I) { /* noop */ }
508
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000509 // Helpers for visitSwitch
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000510 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000511 CaseRecVector& WorkList,
512 Value* SV,
513 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000514 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000515 CaseRecVector& WorkList,
516 Value* SV,
517 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000518 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000519 CaseRecVector& WorkList,
520 Value* SV,
521 MachineBasicBlock* Default);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000522 bool handleBitTestsSwitchCase(CaseRec& CR,
523 CaseRecVector& WorkList,
524 Value* SV,
525 MachineBasicBlock* Default);
Nate Begemaned728c12006-03-27 01:32:24 +0000526 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000527 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
528 void visitBitTestCase(MachineBasicBlock* NextMBB,
529 unsigned Reg,
530 SelectionDAGISel::BitTestCase &B);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000531 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov70378262007-03-25 15:07:15 +0000532 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
533 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemaned728c12006-03-27 01:32:24 +0000534
Chris Lattner7a60d912005-01-07 07:47:53 +0000535 // These all get lowered before this pass.
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000536 void visitInvoke(InvokeInst &I);
537 void visitUnwind(UnwindInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000538
Dan Gohmana8665142007-06-25 16:23:39 +0000539 void visitBinary(User &I, unsigned OpCode);
Nate Begeman127321b2005-11-18 07:42:56 +0000540 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000541 void visitAdd(User &I) {
Dan Gohmana8665142007-06-25 16:23:39 +0000542 if (I.getType()->isFPOrFPVector())
543 visitBinary(I, ISD::FADD);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000544 else
Dan Gohmana8665142007-06-25 16:23:39 +0000545 visitBinary(I, ISD::ADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000546 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000547 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000548 void visitMul(User &I) {
Dan Gohmana8665142007-06-25 16:23:39 +0000549 if (I.getType()->isFPOrFPVector())
550 visitBinary(I, ISD::FMUL);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000551 else
Dan Gohmana8665142007-06-25 16:23:39 +0000552 visitBinary(I, ISD::MUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000553 }
Dan Gohmana8665142007-06-25 16:23:39 +0000554 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); }
Reid Spencer2eadb532007-01-21 00:29:26 +0000563 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000564 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
565 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000566 void visitICmp(User &I);
567 void visitFCmp(User &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000568 // 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);
Chris Lattner7a60d912005-01-07 07:47:53 +0000581
Chris Lattner67271862006-03-29 00:11:43 +0000582 void visitExtractElement(User &I);
583 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000584 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000585
Chris Lattner7a60d912005-01-07 07:47:53 +0000586 void visitGetElementPtr(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000587 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000588
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);
Chris Lattner476e67b2006-01-26 22:24:51 +0000596 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000597 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000598 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000599
Chris Lattner7a60d912005-01-07 07:47:53 +0000600 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000601 void visitVAArg(VAArgInst &I);
602 void visitVAEnd(CallInst &I);
603 void visitVACopy(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000604
Chris Lattner875def92005-01-11 05:56:49 +0000605 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000606
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
Dan Gohmand258e802007-07-05 20:12:34 +0000618
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,
Dan Gohmand258e802007-07-05 20:12:34 +0000626 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];
Dan Gohmanf8f531b2007-07-09 20:59:04 +0000635 if (!DAG.getTargetLoweringInfo().isLittleEndian())
Dan Gohmand258e802007-07-05 20:12:34 +0000636 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,
Dan Gohmanf8f531b2007-07-09 20:59:04 +0000696 PartVT, IntermediateVT);
Dan Gohmand258e802007-07-05 20:12:34 +0000697 } else if (NumParts > 0) {
698 // If the intermediate type was expanded, build the intermediate operands
699 // from the parts.
Dan Gohman4ff9fb12007-07-30 19:09:17 +0000700 assert(NumParts % NumIntermediates == 0 &&
Dan Gohmand258e802007-07-05 20:12:34 +0000701 "Must expand into a divisible number of parts!");
Dan Gohman4ff9fb12007-07-30 19:09:17 +0000702 unsigned Factor = NumParts / NumIntermediates;
Dan Gohmand258e802007-07-05 20:12:34 +0000703 for (unsigned i = 0; i != NumIntermediates; ++i)
704 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
Dan Gohmanf8f531b2007-07-09 20:59:04 +0000705 PartVT, IntermediateVT);
Dan Gohmand258e802007-07-05 20:12:34 +0000706 }
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 Gohman4ff9fb12007-07-30 19:09:17 +0000713 ValueVT, &Ops[0], NumIntermediates);
Dan Gohmand258e802007-07-05 20:12:34 +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,
Dan Gohmanf8f531b2007-07-09 20:59:04 +0000722 MVT::ValueType PartVT) {
Dan Gohmana17799a2007-08-10 14:59:38 +0000723 TargetLowering &TLI = DAG.getTargetLoweringInfo();
724 MVT::ValueType PtrVT = TLI.getPointerTy();
Dan Gohmand258e802007-07-05 20:12:34 +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 Gohmana17799a2007-08-10 14:59:38 +0000732 DAG.getConstant(i, PtrVT));
Dan Gohmanf8f531b2007-07-09 20:59:04 +0000733 if (!DAG.getTargetLoweringInfo().isLittleEndian())
Dan Gohmand258e802007-07-05 20:12:34 +0000734 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 Gohmana17799a2007-08-10 14:59:38 +0000783 PtrVT));
Dan Gohmand258e802007-07-05 20:12:34 +0000784 else
785 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
786 IntermediateVT, Val,
Dan Gohmana17799a2007-08-10 14:59:38 +0000787 DAG.getConstant(i, PtrVT));
Dan Gohmand258e802007-07-05 20:12:34 +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)
Dan Gohmanf8f531b2007-07-09 20:59:04 +0000794 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohmand258e802007-07-05 20:12:34 +0000795 } 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)
Dan Gohmanf8f531b2007-07-09 20:59:04 +0000802 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohmand258e802007-07-05 20:12:34 +0000803 }
804}
805
806
Chris Lattner8471b152006-03-16 19:57:50 +0000807SDOperand 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);
Chris Lattner79084302007-02-04 01:31:47 +0000816 SDOperand N1 = NodeMap[V];
817 assert(N1.Val && "visit didn't populate the ValueMap!");
818 return N1;
Chris Lattner8471b152006-03-16 19:57:50 +0000819 } 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)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000824 if (!isa<VectorType>(VTy))
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000825 return N = DAG.getNode(ISD::UNDEF, VT);
826
Dan Gohmana8665142007-06-25 16:23:39 +0000827 // Create a BUILD_VECTOR of undef nodes.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000828 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000829 unsigned NumElements = PTy->getNumElements();
830 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
831
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000832 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000833 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
834
835 // Create a VConstant node with generic Vector type.
Dan Gohmana8665142007-06-25 16:23:39 +0000836 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
837 return N = DAG.getNode(ISD::BUILD_VECTOR, VT,
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000838 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000839 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
840 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencerd84d35b2007-02-15 02:26:10 +0000841 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner8471b152006-03-16 19:57:50 +0000842 unsigned NumElements = PTy->getNumElements();
843 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000844
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
Dan Gohman06c60b62007-07-16 14:29:03 +0000847 // the vector constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000848 SmallVector<SDOperand, 8> Ops;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000849 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000850 for (unsigned i = 0; i != NumElements; ++i)
851 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000852 } else {
Dan Gohman06c60b62007-07-16 14:29:03 +0000853 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Chris Lattner8471b152006-03-16 19:57:50 +0000854 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
Dan Gohmana8665142007-06-25 16:23:39 +0000862 // 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],
Chris Lattner79084302007-02-04 01:31:47 +0000865 Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000866 } else {
867 // Canonicalize all constant ints to be unsigned.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000868 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000869 }
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
Chris Lattner8c504cf2007-02-25 18:40:32 +0000879 unsigned InReg = FuncInfo.ValueMap[V];
880 assert(InReg && "Value not in map!");
Chris Lattner8471b152006-03-16 19:57:50 +0000881
Dan Gohman78677932007-06-28 23:29:44 +0000882 MVT::ValueType RegisterVT = TLI.getRegisterType(VT);
883 unsigned NumRegs = TLI.getNumRegisters(VT);
Chris Lattner5fe1f542006-03-31 02:06:56 +0000884
Dan Gohman78677932007-06-28 23:29:44 +0000885 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);
Chris Lattner8471b152006-03-16 19:57:50 +0000893}
894
895
Chris Lattner7a60d912005-01-07 07:47:53 +0000896void SelectionDAGLowering::visitRet(ReturnInst &I) {
897 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000898 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000899 return;
900 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000901 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000902 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
Dan Gohmand258e802007-07-05 20:12:34 +0000907 // the full width of a register, since getCopyToParts and Legalize will use
908 // ANY_EXTEND rather than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000909 // 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.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000911 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;
Reid Spencere63b6512006-12-31 05:55:36 +0000918 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +0000919 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Reid Spencere6f81872007-01-03 16:49:33 +0000920 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencera472f662007-04-11 02:44:20 +0000921 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
Reid Spencer0917adf2007-01-03 04:25:33 +0000922 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencera472f662007-04-11 02:44:20 +0000923 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
Reid Spencere63b6512006-12-31 05:55:36 +0000924 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer2a34b912007-01-03 05:03:05 +0000925 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Dan Gohmand258e802007-07-05 20:12:34 +0000926 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);
Dan Gohmanf8f531b2007-07-09 20:59:04 +0000933 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT);
Dan Gohmand258e802007-07-05 20:12:34 +0000934 for (unsigned i = 0; i < NumParts; ++i) {
935 NewValues.push_back(Parts[i]);
936 NewValues.push_back(DAG.getConstant(false, MVT::i32));
937 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000938 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000939 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000940 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
941 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000942}
943
Chris Lattnered0110b2006-10-27 21:36:01 +0000944/// 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
Chris Lattner84a03502006-10-27 23:50:33 +0000958bool 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
Chris Lattnere60ae822006-10-29 21:01:20 +0000985static 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
Chris Lattnered0110b2006-10-27 21:36:01 +0000991/// FindMergedConditions - If Cond is an expression like
992void SelectionDAGLowering::FindMergedConditions(Value *Cond,
993 MachineBasicBlock *TBB,
994 MachineBasicBlock *FBB,
995 MachineBasicBlock *CurBB,
996 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000997 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencer266e42b2006-12-23 06:05:41 +0000998 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattnered0110b2006-10-27 21:36:01 +0000999
Reid Spencer266e42b2006-12-23 06:05:41 +00001000 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1001 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +00001002 BOp->getParent() != CurBB->getBasicBlock() ||
1003 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1004 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +00001005 const BasicBlock *BB = CurBB->getBasicBlock();
1006
Reid Spencer266e42b2006-12-23 06:05:41 +00001007 // 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
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001011 // 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)))) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001016 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 {
Chris Lattner79084302007-02-04 01:31:47 +00001058 Condition = ISD::SETEQ; // silence warning.
Reid Spencer266e42b2006-12-23 06:05:41 +00001059 assert(0 && "Unknown compare instruction");
Chris Lattnered0110b2006-10-27 21:36:01 +00001060 }
1061
Chris Lattnered0110b2006-10-27 21:36:01 +00001062 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001063 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +00001064 SwitchCases.push_back(CB);
1065 return;
1066 }
1067
1068 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001069 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001070 NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +00001071 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +00001072 return;
1073 }
1074
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001075
1076 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +00001077 MachineFunction::iterator BBI = CurBB;
1078 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1079 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1080
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001081 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 //
Chris Lattnered0110b2006-10-27 21:36:01 +00001089
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001090 // 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 }
Chris Lattnered0110b2006-10-27 21:36:01 +00001112}
1113
Chris Lattner427301f2006-10-31 22:37:42 +00001114/// 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
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001121 // 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
Chris Lattner427301f2006-10-31 22:37:42 +00001130 return true;
1131}
1132
Chris Lattner7a60d912005-01-07 07:47:53 +00001133void SelectionDAGLowering::visitBr(BranchInst &I) {
1134 // Update machine-CFG edges.
1135 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +00001136
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)
Chris Lattner4108bb02005-01-17 19:43:36 +00001146 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +00001147 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +00001148
Chris Lattner963ddad2006-10-24 17:57:59 +00001149 // 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();
Chris Lattner963ddad2006-10-24 17:57:59 +00001158 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +00001159
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() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001177 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001178 BOp->getOpcode() == Instruction::Or)) {
1179 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001180 // 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
Chris Lattner427301f2006-10-31 22:37:42 +00001185 // Allow some cases to be rejected.
1186 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001187 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;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001196 }
1197
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001198 // 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
Chris Lattner427301f2006-10-31 22:37:42 +00001203 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001204 }
1205 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001206
1207 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001208 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001209 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner61bcf912006-10-24 18:07:37 +00001210 // Use visitSwitchCase to actually insert the fast branch sequence for this
1211 // cond branch.
1212 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001213}
1214
Nate Begemaned728c12006-03-27 01:32:24 +00001215/// 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) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001218 SDOperand Cond;
1219 SDOperand CondLHS = getValue(CB.CmpLHS);
1220
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001221 // 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");
Anton Korobeynikov70378262007-03-25 15:07:15 +00001234
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001235 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
Nate Begemaned728c12006-03-27 01:32:24 +00001251 // 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.
Chris Lattner963ddad2006-10-24 17:57:59 +00001260 if (CB.TrueBB == NextBlock) {
1261 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001262 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,
Chris Lattner963ddad2006-10-24 17:57:59 +00001266 DAG.getBasicBlock(CB.TrueBB));
1267 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001268 DAG.setRoot(BrCond);
1269 else
1270 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001271 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001272 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001273 CurMBB->addSuccessor(CB.TrueBB);
1274 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001275}
1276
Anton Korobeynikov70378262007-03-25 15:07:15 +00001277/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001278void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001279 // Emit the code for the jump table
Scott Michel4cfa6162007-04-24 01:24:20 +00001280 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001281 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001282 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;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001287}
1288
Anton Korobeynikov70378262007-03-25 15:07:15 +00001289/// 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.
Dan Gohmana8665142007-06-25 16:23:39 +00001306 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
Anton Korobeynikov70378262007-03-25 15:07:15 +00001307 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,
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001336 DAG.getBasicBlock(JT.MBB)));
1337
1338 return;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001339}
1340
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001341/// 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;
Dan Gohmana8665142007-06-25 16:23:39 +00001356 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001357 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}
Anton Korobeynikov70378262007-03-25 15:07:15 +00001428
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001429void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1430 // Retrieve successors.
1431 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sands97f72362007-06-13 05:51:31 +00001432 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands61166502007-06-06 10:05:18 +00001433
Duncan Sands97f72362007-06-13 05:51:31 +00001434 LowerCallTo(I, I.getCalledValue()->getType(),
1435 I.getCallingConv(),
1436 false,
1437 getValue(I.getOperand(0)),
1438 3, LandingPad);
Duncan Sands61166502007-06-06 10:05:18 +00001439
Duncan Sands97f72362007-06-13 05:51:31 +00001440 // 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));
Jim Laskey14059d92007-02-25 21:43:59 +00001446 }
Duncan Sands97f72362007-06-13 05:51:31 +00001447
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);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001455}
1456
1457void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1458}
1459
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001460/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001461/// small case ranges).
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001462bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001463 CaseRecVector& WorkList,
1464 Value* SV,
1465 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001466 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;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001470 if (Size > 3)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001471 return false;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001472
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001473 // 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
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001481 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.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001490 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001491 // 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) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001494 if (I->BB == NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001495 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 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001514
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);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001527
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 }
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001539
1540 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001541}
1542
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001543static inline bool areJTsAllowed(const TargetLowering &TLI) {
1544 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1545 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1546}
1547
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001548/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001549bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001550 CaseRecVector& WorkList,
1551 Value* SV,
1552 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001553 Case& FrontCase = *CR.Range.first;
1554 Case& BackCase = *(CR.Range.second-1);
1555
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001556 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();
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001563
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001564 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001565 return false;
1566
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001567 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1568 if (Density < 0.4)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001569 return false;
1570
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001571 DOUT << "Lowering jump table\n"
1572 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001573 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001574
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001575 // Get the MachineFunction which holds the current MBB. This is used when
1576 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001577 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001578
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
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001586 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1587
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001588 // 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
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001598 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001599 // 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;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001603 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;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001611 } else {
1612 DestBBs.push_back(Default);
1613 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001614 }
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001615
1616 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001617 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001618 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
Scott Michel4cfa6162007-04-24 01:24:20 +00001632 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001633 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));
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001639
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001640 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001641}
1642
1643/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1644/// 2 subtrees.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001645bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001646 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
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001667 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1668 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001669 double FMetric = 0;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001670 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001671
1672 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1673 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001674 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;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001681 DOUT << "Selecting best pivot: \n"
1682 << "First: " << First << ", Last: " << Last <<"\n"
1683 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001684 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001685 J!=E; ++I, ++J) {
1686 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1687 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001688 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001689 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1690 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikovda964a22007-04-09 21:57:03 +00001691 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001692 // 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) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001698 Pivot = J;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001699 FMetric = Metric;
1700 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001701 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001702
1703 LSize += J->size();
1704 RSize -= J->size();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001705 }
Anton Korobeynikov192d09c2007-05-09 20:07:08 +00001706 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 }
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001712
1713 CaseRange LHSR(CR.Range.first, Pivot);
1714 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001715 Constant *C = Pivot->Low;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001716 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 &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001725 LHSR.first->High == CR.GE &&
1726 cast<ConstantInt>(C)->getSExtValue() ==
1727 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1728 TrueBB = LHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001729 } 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 &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001740 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1741 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1742 FalseBB = RHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001743 } 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.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001752 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1753 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001754
1755 if (CR.CaseBB == CurMBB)
1756 visitSwitchCase(CB);
1757 else
1758 SwitchCases.push_back(CB);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001759
1760 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001761}
1762
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001763/// 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,
Chris Lattner7196f092007-04-14 02:26:56 +00001769 MachineBasicBlock* Default){
Dan Gohman1796f1f2007-05-18 17:52:13 +00001770 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001771
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
Anton Korobeynikovd7ae7f12007-04-26 20:44:04 +00001809 if (range>=IntPtrBits ||
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001810 (!(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 &&
Anton Korobeynikov8a1a84f2007-04-14 13:25:55 +00001822 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001823 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++) {
Anton Korobeynikov8a1a84f2007-04-14 13:25:55 +00001847 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001848 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,
Jeff Cohen0475f3b2007-04-09 14:32:59 +00001875 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001876 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
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001887// 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)
David Greene4c1e6f32007-06-29 03:42:23 +00001903 // Must recompute end() each iteration because it may be
1904 // invalidated by erase if we hold on to it
David Greene9468bfd2007-06-29 02:49:11 +00001905 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001906 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) {
Nate Begemaned728c12006-03-27 01:32:24 +00001931 // Figure out which block is immediately after the current one.
1932 MachineBasicBlock *NextBlock = 0;
1933 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001934
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001935 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattner6d6fc262006-10-22 21:36:53 +00001936
Nate Begemaned728c12006-03-27 01:32:24 +00001937 // If there is only the default destination, branch to it if it is not the
1938 // next basic block. Otherwise, just fall through.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001939 if (SI.getNumOperands() == 2) {
Nate Begemaned728c12006-03-27 01:32:24 +00001940 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001941
Nate Begemaned728c12006-03-27 01:32:24 +00001942 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001943 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001944 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001945 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001946
Chris Lattner6d6fc262006-10-22 21:36:53 +00001947 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001948 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.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001954 CaseVector Cases;
1955 unsigned numCmps = Clusterify(Cases, SI);
1956 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1957 << ". Total compares: " << numCmps << "\n";
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001958
Nate Begemaned728c12006-03-27 01:32:24 +00001959 // 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.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001962 Value *SV = SI.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001963
Nate Begemaned728c12006-03-27 01:32:24 +00001964 // Push the initial CaseRec onto the worklist
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001965 CaseRecVector WorkList;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001966 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1967
1968 while (!WorkList.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00001969 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov70378262007-03-25 15:07:15 +00001970 CaseRec CR = WorkList.back();
1971 WorkList.pop_back();
Anton Korobeynikov70378262007-03-25 15:07:15 +00001972
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001973 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1974 continue;
1975
Anton Korobeynikov70378262007-03-25 15:07:15 +00001976 // If the range has few cases (two or less) emit a series of specific
1977 // tests.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001978 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1979 continue;
1980
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001981 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov70378262007-03-25 15:07:15 +00001982 // target supports indirect branches, then emit a jump table rather than
1983 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001984 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);
Nate Begemaned728c12006-03-27 01:32:24 +00001990 }
1991}
1992
Anton Korobeynikov70378262007-03-25 15:07:15 +00001993
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001994void SelectionDAGLowering::visitSub(User &I) {
1995 // -0.0 - X --> fneg
Reid Spencer2eadb532007-01-21 00:29:26 +00001996 const Type *Ty = I.getType();
Reid Spencerd84d35b2007-02-15 02:26:10 +00001997 if (isa<VectorType>(Ty)) {
Dan Gohmana8665142007-06-25 16:23:39 +00001998 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
1999 const VectorType *DestTy = cast<VectorType>(I.getType());
2000 const Type *ElTy = DestTy->getElementType();
Evan Chengfa68d062007-06-29 21:44:35 +00002001 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 }
Dan Gohmana8665142007-06-25 16:23:39 +00002010 }
2011 }
2012 }
2013 if (Ty->isFloatingPoint()) {
Chris Lattner6f3b5772005-09-28 22:28:18 +00002014 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 }
Dan Gohmana8665142007-06-25 16:23:39 +00002020 }
2021
2022 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00002023}
2024
Dan Gohmana8665142007-06-25 16:23:39 +00002025void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00002026 SDOperand Op1 = getValue(I.getOperand(0));
2027 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer2eadb532007-01-21 00:29:26 +00002028
2029 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00002030}
2031
Nate Begeman127321b2005-11-18 07:42:56 +00002032void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2033 SDOperand Op1 = getValue(I.getOperand(0));
2034 SDOperand Op2 = getValue(I.getOperand(1));
2035
Dan Gohmana8665142007-06-25 16:23:39 +00002036 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2037 MVT::getSizeInBits(Op2.getValueType()))
Reid Spencer2341c222007-02-02 02:16:23 +00002038 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);
Nate Begeman127321b2005-11-18 07:42:56 +00002041
Chris Lattner7a60d912005-01-07 07:47:53 +00002042 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2043}
2044
Reid Spencerd9436b62006-11-20 01:22:35 +00002045void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002046 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));
Reid Spencerd9436b62006-11-20 01:22:35 +00002053 ISD::CondCode Opcode;
Reid Spencer266e42b2006-12-23 06:05:41 +00002054 switch (predicate) {
Reid Spencerd9436b62006-11-20 01:22:35 +00002055 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) {
Reid Spencer266e42b2006-12-23 06:05:41 +00002074 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());
Chris Lattner7a60d912005-01-07 07:47:53 +00002079 SDOperand Op1 = getValue(I.getOperand(0));
2080 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00002081 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));
Chris Lattner7a60d912005-01-07 07:47:53 +00002109}
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));
Dan Gohmana8665142007-06-25 16:23:39 +00002115 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2116 TrueVal, FalseVal));
Chris Lattner7a60d912005-01-07 07:47:53 +00002117}
2118
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002119
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.
Chris Lattner7a60d912005-01-07 07:47:53 +00002188 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00002189 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00002190 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002191 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}
Chris Lattner7a60d912005-01-07 07:47:53 +00002199
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002200void 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());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002216
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.
Chris Lattner7a60d912005-01-07 07:47:53 +00002223}
2224
Chris Lattner67271862006-03-29 00:11:43 +00002225void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00002226 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
Dan Gohmana8665142007-06-25 16:23:39 +00002231 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2232 TLI.getValueType(I.getType()),
2233 InVec, InVal, InIdx));
Chris Lattner32206f52006-03-18 01:44:44 +00002234}
2235
Chris Lattner67271862006-03-29 00:11:43 +00002236void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00002237 SDOperand InVec = getValue(I.getOperand(0));
2238 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2239 getValue(I.getOperand(1)));
Dan Gohmana8665142007-06-25 16:23:39 +00002240 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00002241 TLI.getValueType(I.getType()), InVec, InIdx));
2242}
Chris Lattner32206f52006-03-18 01:44:44 +00002243
Chris Lattner098c01e2006-04-08 04:15:24 +00002244void 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
Dan Gohmana8665142007-06-25 16:23:39 +00002249 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2250 TLI.getValueType(I.getType()),
2251 V1, V2, Mask));
Chris Lattner098c01e2006-04-08 04:15:24 +00002252}
2253
2254
Chris Lattner7a60d912005-01-07 07:47:53 +00002255void SelectionDAGLowering::visitGetElementPtr(User &I) {
2256 SDOperand N = getValue(I.getOperand(0));
2257 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00002258
2259 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2260 OI != E; ++OI) {
2261 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00002262 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002263 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00002264 if (Field) {
2265 // N = N + Offset
Chris Lattnerc473d8e2007-02-10 19:55:17 +00002266 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner7a60d912005-01-07 07:47:53 +00002267 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00002268 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00002269 }
2270 Ty = StTy->getElementType(Field);
2271 } else {
2272 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00002273
Chris Lattner43535a12005-11-09 04:45:33 +00002274 // If this is a constant subscript, handle it quickly.
2275 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002276 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00002277 uint64_t Offs =
Evan Cheng8ec52832007-01-05 01:46:20 +00002278 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00002279 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2280 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00002281 }
Chris Lattner43535a12005-11-09 04:45:33 +00002282
2283 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00002284 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00002285 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()) {
Reid Spencere63b6512006-12-31 05:55:36 +00002290 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner43535a12005-11-09 04:45:33 +00002291 } 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,
Chris Lattner41fd6d52005-11-09 16:50:40 +00002299 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00002300 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);
Chris Lattner7a60d912005-01-07 07:47:53 +00002307 }
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();
Owen Anderson20a631f2006-05-03 01:29:57 +00002319 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner50ee0e42007-01-20 22:35:55 +00002320 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +00002321 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner50ee0e42007-01-20 22:35:55 +00002322 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00002323
2324 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00002325 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);
Chris Lattner7a60d912005-01-07 07:47:53 +00002330
Chris Lattnereccb73d2005-01-22 23:04:37 +00002331 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00002332 getIntPtrConstant(TySize));
2333
Evan Cheng95667c52007-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.
Chris Lattner7a60d912005-01-07 07:47:53 +00002337 unsigned StackAlign =
2338 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng95667c52007-08-16 23:46:29 +00002339 if (Align <= StackAlign)
Chris Lattner7a60d912005-01-07 07:47:53 +00002340 Align = 0;
Evan Cheng95667c52007-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)));
Chris Lattner7a60d912005-01-07 07:47:53 +00002349
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002350 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00002351 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2352 MVT::Other);
2353 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner79084302007-02-04 01:31:47 +00002354 setValue(&I, DSA);
2355 DAG.setRoot(DSA.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002356
2357 // Inform the Frame Information that we have just allocated a variable-sized
2358 // object.
2359 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2360}
2361
Chris Lattner7a60d912005-01-07 07:47:53 +00002362void SelectionDAGLowering::visitLoad(LoadInst &I) {
2363 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00002364
Chris Lattner4d9651c2005-01-17 22:19:26 +00002365 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 }
Chris Lattner4024c002006-03-15 22:19:46 +00002372
Evan Chenge71fe34d2006-10-09 20:57:25 +00002373 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb8af6d582007-04-22 23:15:30 +00002374 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner4024c002006-03-15 22:19:46 +00002375}
2376
2377SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00002378 const Value *SV, SDOperand Root,
Christopher Lamb8af6d582007-04-22 23:15:30 +00002379 bool isVolatile,
2380 unsigned Alignment) {
Dan Gohmana8665142007-06-25 16:23:39 +00002381 SDOperand L =
2382 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2383 isVolatile, Alignment);
Chris Lattner4d9651c2005-01-17 22:19:26 +00002384
Chris Lattner4024c002006-03-15 22:19:46 +00002385 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00002386 DAG.setRoot(L.getValue(1));
2387 else
2388 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00002389
2390 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00002391}
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));
Evan Cheng258657e2006-12-20 01:27:29 +00002398 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb8af6d582007-04-22 23:15:30 +00002399 I.isVolatile(), I.getAlignment()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002400}
2401
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002402/// 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
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002411// 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
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002420/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2421/// node.
2422void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2423 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00002424 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002425 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002426
2427 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002428 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002429 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 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002437
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));
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002444 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());
Dan Gohmana8665142007-06-25 16:23:39 +00002452 if (MVT::isVector(VT)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002453 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002454 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
Chris Lattnerbd887772006-08-14 23:53:35 +00002466 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2467
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002468 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00002469 SDOperand Result;
2470 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00002471 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2472 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002473 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00002474 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2475 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002476 else
Chris Lattnerbd887772006-08-14 23:53:35 +00002477 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2478 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002479
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002480 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 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002487 if (I.getType() != Type::VoidTy) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002488 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Dan Gohmana8665142007-06-25 16:23:39 +00002489 MVT::ValueType VT = TLI.getValueType(PTy);
2490 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002491 }
2492 setValue(&I, Result);
2493 }
2494}
2495
Duncan Sands81df18a2007-07-06 09:10:03 +00002496/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandsfe806382007-07-04 20:52:51 +00002497static GlobalVariable *ExtractTypeInfo (Value *V) {
Duncan Sands81df18a2007-07-06 09:10:03 +00002498 V = IntrinsicInst::StripPointerCasts(V);
2499 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Duncan Sandsfe806382007-07-04 20:52:51 +00002500 assert (GV || isa<ConstantPointerNull>(V) &&
2501 "TypeInfo must be a global variable or NULL");
2502 return GV;
2503}
2504
Duncan Sands92bf2c62007-06-15 19:04:19 +00002505/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandsfe806382007-07-04 20:52:51 +00002506/// call, and add them to the specified machine basic block.
Duncan Sands92bf2c62007-06-15 19:04:19 +00002507static 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;
Duncan Sandsfe806382007-07-04 20:52:51 +00002519 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 Sandsef5a6542007-08-27 15:47:50 +00002524 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandsfe806382007-07-04 20:52:51 +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 Sandsef5a6542007-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 }
Duncan Sandsfe806382007-07-04 20:52:51 +00002546
2547 N = i;
2548 }
Duncan Sands92bf2c62007-06-15 19:04:19 +00002549 }
Duncan Sandsfe806382007-07-04 20:52:51 +00002550
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)));
Duncan Sands92bf2c62007-06-15 19:04:19 +00002555 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandsfe806382007-07-04 20:52:51 +00002556 }
Duncan Sands92bf2c62007-06-15 19:04:19 +00002557}
2558
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002559/// 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) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002565 default:
2566 // By default, turn this into a target intrinsic node.
2567 visitTargetIntrinsic(I, Intrinsic);
2568 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002569 case Intrinsic::vastart: visitVAStart(I); return 0;
2570 case Intrinsic::vaend: visitVAEnd(I); return 0;
2571 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemaneda59972007-01-29 22:58:52 +00002572 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;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002580 case Intrinsic::setjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002581 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002582 break;
2583 case Intrinsic::longjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002584 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002585 break;
Chris Lattner093c1592006-03-03 00:00:25 +00002586 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;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002598
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002599 case Intrinsic::dbg_stoppoint: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002600 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002601 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002602 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002603 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00002604
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002605 Ops[0] = getRoot();
2606 Ops[1] = getValue(SPI.getLineValue());
2607 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00002608
Jim Laskeyc56315c2007-01-26 21:22:28 +00002609 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00002610 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00002611 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2612
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002613 Ops[3] = DAG.getString(CompileUnit->getFileName());
2614 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00002615
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002616 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002617 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002618
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002619 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00002620 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002621 case Intrinsic::dbg_region_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002622 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002623 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002624 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2625 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002626 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002627 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002628 }
2629
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002630 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002631 }
2632 case Intrinsic::dbg_region_end: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002633 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002634 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002635 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2636 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002637 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002638 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002639 }
2640
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002641 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002642 }
2643 case Intrinsic::dbg_func_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002644 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002645 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002646 if (MMI && FSI.getSubprogram() &&
2647 MMI->Verify(FSI.getSubprogram())) {
2648 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002649 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002650 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002651 }
2652
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002653 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002654 }
2655 case Intrinsic::dbg_declare: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002656 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002657 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002658 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00002659 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002660 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeyc56315c2007-01-26 21:22:28 +00002661 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00002662 }
2663
2664 return 0;
2665 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002666
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002667 case Intrinsic::eh_exception: {
Evan Cheng77f541d2007-06-27 18:45:32 +00002668 if (ExceptionHandling) {
Duncan Sands003c0b12007-07-06 09:18:59 +00002669 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 }
Jim Laskey504e9942007-02-22 15:38:06 +00002674 // 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));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002681 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002682 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002683 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002684 return 0;
2685 }
2686
Duncan Sandsfe806382007-07-04 20:52:51 +00002687 case Intrinsic::eh_selector:{
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002688 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002689
Duncan Sands92bf2c62007-06-15 19:04:19 +00002690 if (ExceptionHandling && MMI) {
2691 if (CurMBB->isLandingPad())
2692 addCatchInfo(I, MMI, CurMBB);
Evan Cheng77f541d2007-06-27 18:45:32 +00002693 else {
Duncan Sands92bf2c62007-06-15 19:04:19 +00002694#ifndef NDEBUG
Duncan Sands92bf2c62007-06-15 19:04:19 +00002695 FuncInfo.CatchInfoLost.insert(&I);
2696#endif
Duncan Sands003c0b12007-07-06 09:18:59 +00002697 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2698 unsigned Reg = TLI.getExceptionSelectorRegister();
2699 if (Reg) CurMBB->addLiveIn(Reg);
Evan Cheng77f541d2007-06-27 18:45:32 +00002700 }
Jim Laskey504e9942007-02-22 15:38:06 +00002701
2702 // Insert the EHSELECTION instruction.
Anton Korobeynikov11940fb2007-05-02 22:15:48 +00002703 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Jim Laskey504e9942007-02-22 15:38:06 +00002704 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));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002710 } else {
Anton Korobeynikov11940fb2007-05-02 22:15:48 +00002711 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002712 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002713
2714 return 0;
2715 }
2716
2717 case Intrinsic::eh_typeid_for: {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002718 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002719
Jim Laskey504e9942007-02-22 15:38:06 +00002720 if (MMI) {
2721 // Find the type id for the given typeinfo.
Duncan Sandsfe806382007-07-04 20:52:51 +00002722 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands4cb9eb82007-05-04 17:12:26 +00002723
Jim Laskey504e9942007-02-22 15:38:06 +00002724 unsigned TypeID = MMI->getTypeIDFor(GV);
2725 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002726 } else {
Duncan Sands9d974202007-07-06 14:46:23 +00002727 // Return something different to eh_selector.
2728 setValue(&I, DAG.getConstant(1, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002729 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002730
2731 return 0;
2732 }
2733
Anton Korobeynikov383a3242007-07-14 14:06:15 +00002734 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 Korobeynikov97cdac82007-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
Anton Korobeynikov383a3242007-07-14 14:06:15 +00002770 SDOperand Offset = DAG.getNode(ISD::ADD,
2771 TLI.getPointerTy(),
2772 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
Anton Korobeynikov97cdac82007-08-23 07:21:06 +00002773 TLI.getPointerTy()),
2774 CfaArg);
Anton Korobeynikov383a3242007-07-14 14:06:15 +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
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002789 case Intrinsic::sqrt_f32:
2790 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002791 setValue(&I, DAG.getNode(ISD::FSQRT,
2792 getValue(I.getOperand(1)).getValueType(),
2793 getValue(I.getOperand(1))));
2794 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00002795 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;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002802 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 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002807 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002808 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002809 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2810 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2811 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002812 setValue(&I, Tmp);
2813 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002814 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002815 }
Chris Lattnerf269d842007-04-10 03:20:39 +00002816 case Intrinsic::part_select: {
Reid Spencer85460ac2007-04-05 01:20:18 +00002817 // Currently not implemented: just abort
Reid Spencerc6251a72007-04-12 02:48:46 +00002818 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");
Reid Spencer85460ac2007-04-05 01:20:18 +00002824 abort();
Reid Spencercce90f52007-04-04 23:48:25 +00002825 }
Reid Spencer3a0843e2007-04-01 07:34:11 +00002826 case Intrinsic::bswap:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002827 setValue(&I, DAG.getNode(ISD::BSWAP,
2828 getValue(I.getOperand(1)).getValueType(),
2829 getValue(I.getOperand(1))));
2830 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002831 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);
Reid Spencer3a0843e2007-04-01 07:34:11 +00002835 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002836 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002837 }
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);
Reid Spencer3a0843e2007-04-01 07:34:11 +00002842 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002843 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002844 }
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);
Reid Spencer3a0843e2007-04-01 07:34:11 +00002849 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002850 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002851 }
Chris Lattnerb3266452006-01-13 02:50:02 +00002852 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002853 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002854 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2855 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002856 setValue(&I, Tmp);
2857 DAG.setRoot(Tmp.getValue(1));
2858 return 0;
2859 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002860 case Intrinsic::stackrestore: {
2861 SDOperand Tmp = getValue(I.getOperand(1));
2862 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002863 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002864 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002865 case Intrinsic::prefetch:
2866 // FIXME: Currently discarding prefetches.
2867 return 0;
Tanya Lattnere199f972007-06-15 22:26:58 +00002868
2869 case Intrinsic::var_annotation:
2870 // Discard annotate attributes
2871 return 0;
Duncan Sands644f9172007-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 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002894 }
2895}
2896
2897
Jim Laskey31fef782007-02-23 21:45:01 +00002898void SelectionDAGLowering::LowerCallTo(Instruction &I,
2899 const Type *CalledValueTy,
2900 unsigned CallingConv,
2901 bool IsTailCall,
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002902 SDOperand Callee, unsigned OpIdx,
2903 MachineBasicBlock *LandingPad) {
Jim Laskey31fef782007-02-23 21:45:01 +00002904 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey504e9942007-02-22 15:38:06 +00002905 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Reid Spencer71b79e32007-04-09 06:17:21 +00002906 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002907 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2908 unsigned BeginLabel = 0, EndLabel = 0;
2909
Jim Laskey504e9942007-02-22 15:38:06 +00002910 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();
Duncan Sands671e8c42007-05-07 20:49:28 +00002917
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 Sands644f9172007-07-27 12:58:54 +00002923 Entry.isNest = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::Nest);
Rafael Espindola9c3d20d2007-08-20 15:18:24 +00002924 Entry.isByVal = Attrs && Attrs->paramHasAttr(attrInd, ParamAttr::ByVal);
Jim Laskey504e9942007-02-22 15:38:06 +00002925 Args.push_back(Entry);
2926 }
2927
Duncan Sands61166502007-06-06 10:05:18 +00002928 if (ExceptionHandling && MMI) {
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002929 // 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
Jim Laskey504e9942007-02-22 15:38:06 +00002936 std::pair<SDOperand,SDOperand> Result =
2937 TLI.LowerCallTo(getRoot(), I.getType(),
Reid Spencera472f662007-04-11 02:44:20 +00002938 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
Jim Laskey31fef782007-02-23 21:45:01 +00002939 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002940 Callee, Args, DAG);
2941 if (I.getType() != Type::VoidTy)
2942 setValue(&I, Result.first);
2943 DAG.setRoot(Result.second);
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002944
Duncan Sands61166502007-06-06 10:05:18 +00002945 if (ExceptionHandling && MMI) {
Anton Korobeynikov3b327822007-05-23 11:08:31 +00002946 // 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 }
Jim Laskey504e9942007-02-22 15:38:06 +00002955}
2956
2957
Chris Lattner7a60d912005-01-07 07:47:53 +00002958void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002959 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002960 if (Function *F = I.getCalledFunction()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00002961 if (F->isDeclaration())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002962 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();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002968 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")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002980 if (I.getNumOperands() == 2 && // Basic sanity checks.
2981 I.getOperand(1)->getType()->isFloatingPoint() &&
2982 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002983 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002984 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2985 return;
2986 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002987 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002988 if (I.getNumOperands() == 2 && // Basic sanity checks.
2989 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002990 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002991 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002992 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2993 return;
2994 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002995 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002996 if (I.getNumOperands() == 2 && // Basic sanity checks.
2997 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002998 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002999 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00003000 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3001 return;
3002 }
3003 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00003004 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003005 } else if (isa<InlineAsm>(I.getOperand(0))) {
3006 visitInlineAsm(I);
3007 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00003008 }
Misha Brukman835702a2005-04-21 22:36:52 +00003009
Chris Lattner18d2b342005-01-08 22:48:57 +00003010 SDOperand Callee;
3011 if (!RenameFn)
3012 Callee = getValue(I.getOperand(0));
3013 else
3014 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov3b327822007-05-23 11:08:31 +00003015
Jim Laskey31fef782007-02-23 21:45:01 +00003016 LowerCallTo(I, I.getCalledValue()->getType(),
Anton Korobeynikov3b327822007-05-23 11:08:31 +00003017 I.getCallingConv(),
3018 I.isTailCall(),
3019 Callee,
3020 1);
Chris Lattner7a60d912005-01-07 07:47:53 +00003021}
3022
Jim Laskey504e9942007-02-22 15:38:06 +00003023
Dan Gohman78677932007-06-28 23:29:44 +00003024/// 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{
Dan Gohman78677932007-06-28 23:29:44 +00003030 // Copy the legal parts from the registers.
3031 unsigned NumParts = Regs.size();
3032 SmallVector<SDOperand, 8> Parts(NumParts);
Dan Gohman533dd162007-07-02 16:18:06 +00003033 for (unsigned i = 0; i != NumParts; ++i) {
Dan Gohman78677932007-06-28 23:29:44 +00003034 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;
Chris Lattner705948d2006-06-08 18:22:48 +00003041 }
Chris Lattner77f04792007-03-25 05:00:54 +00003042
Dan Gohman78677932007-06-28 23:29:44 +00003043 // Assemble the legal parts into the final value.
Dan Gohmanf8f531b2007-07-09 20:59:04 +00003044 return getCopyFromParts(DAG, &Parts[0], NumParts, RegVT, ValueVT);
Chris Lattner6f87d182006-02-22 22:37:12 +00003045}
3046
Chris Lattner571d9642006-02-23 19:21:04 +00003047/// 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.
Dan Gohman78677932007-06-28 23:29:44 +00003050/// If the Flag pointer is NULL, no flag is used.
Chris Lattner571d9642006-02-23 19:21:04 +00003051void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohman78677932007-06-28 23:29:44 +00003052 SDOperand &Chain, SDOperand *Flag) const {
Dan Gohman78677932007-06-28 23:29:44 +00003053 // Get the list of the values's legal parts.
3054 unsigned NumParts = Regs.size();
3055 SmallVector<SDOperand, 8> Parts(NumParts);
Dan Gohmanf8f531b2007-07-09 20:59:04 +00003056 getCopyToParts(DAG, Val, &Parts[0], NumParts, RegVT);
Dan Gohman78677932007-06-28 23:29:44 +00003057
3058 // Copy the parts into the registers.
Dan Gohman533dd162007-07-02 16:18:06 +00003059 for (unsigned i = 0; i != NumParts; ++i) {
Dan Gohman78677932007-06-28 23:29:44 +00003060 SDOperand Part = Flag ?
Dan Gohmanf8f531b2007-07-09 20:59:04 +00003061 DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag) :
3062 DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
Dan Gohman78677932007-06-28 23:29:44 +00003063 Chain = Part.getValue(0);
3064 if (Flag)
3065 *Flag = Part.getValue(1);
Chris Lattner571d9642006-02-23 19:21:04 +00003066 }
3067}
Chris Lattner6f87d182006-02-22 22:37:12 +00003068
Chris Lattner571d9642006-02-23 19:21:04 +00003069/// 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,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00003073 std::vector<SDOperand> &Ops) const {
Chris Lattnerb49917d2007-04-09 00:33:58 +00003074 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3075 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner571d9642006-02-23 19:21:04 +00003076 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
3077 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
3078}
Chris Lattner6f87d182006-02-22 22:37:12 +00003079
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 *
Chris Lattnerb1124f32006-02-22 23:09:03 +00003084isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3085 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00003086 MVT::ValueType FoundVT = MVT::Other;
3087 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00003088 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
3089 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00003090 MVT::ValueType ThisVT = MVT::Other;
3091
Chris Lattnerb1124f32006-02-22 23:09:03 +00003092 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.
Chris Lattnerb1124f32006-02-22 23:09:03 +00003095 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3096 I != E; ++I) {
3097 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00003098 // 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 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00003106 }
3107 }
3108
Chris Lattnerbec582f2006-04-02 00:24:45 +00003109 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00003110
Chris Lattner6f87d182006-02-22 22:37:12 +00003111 // 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.
Chris Lattnerb1124f32006-02-22 23:09:03 +00003115 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3116 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00003117 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 }
Chris Lattner1558fc62006-02-01 18:59:47 +00003124 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00003125 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00003126}
3127
Chris Lattner1558fc62006-02-01 18:59:47 +00003128
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003129namespace {
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;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003135
3136 /// ConstraintType - Information about the constraint code, e.g. Register,
3137 /// RegisterClass, Memory, Other, Unknown.
3138 TargetLowering::ConstraintType ConstraintType;
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003139
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
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003149 /// 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
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003153 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Chris Lattnerb2e55562007-04-28 21:01:43 +00003154 : InlineAsm::ConstraintInfo(info),
3155 ConstraintType(TargetLowering::C_Unknown),
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003156 CallOperand(0,0), CallOperandVal(0), ConstraintVT(MVT::Other) {
3157 }
Chris Lattneref073322007-04-30 17:16:27 +00003158
3159 void ComputeConstraintToUse(const TargetLowering &TLI);
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003160
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 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003171};
3172} // end anon namespace.
Chris Lattner6f87d182006-02-22 22:37:12 +00003173
Chris Lattneref073322007-04-30 17:16:27 +00003174/// 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
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003222void SelectionDAGLowering::
3223GetRegistersForValue(AsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattner4333f8b2007-04-30 17:29:31 +00003224 std::set<unsigned> &OutputRegs,
3225 std::set<unsigned> &InputRegs) {
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003226 // 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();
Chris Lattner4333f8b2007-04-30 17:29:31 +00003251 std::vector<unsigned> Regs;
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003252
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);
Chris Lattner4333f8b2007-04-30 17:29:31 +00003258
3259 unsigned NumRegs = 1;
3260 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohman04deef32007-06-21 14:42:22 +00003261 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner4333f8b2007-04-30 17:29:31 +00003262 MVT::ValueType RegVT;
3263 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3264
Chris Lattner4333f8b2007-04-30 17:29:31 +00003265
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 }
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003294 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3295 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3296 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003297 }
3298
3299 // Otherwise, if this was a reference to an LLVM register class, create vregs
3300 // for this reference.
3301 std::vector<unsigned> RegClassRegs;
Chris Lattnerf852e332007-06-15 19:11:01 +00003302 const TargetRegisterClass *RC = PhysReg.second;
3303 if (RC) {
Chris Lattner4333f8b2007-04-30 17:29:31 +00003304 // 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.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003307 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)) {
Chris Lattner4333f8b2007-04-30 17:29:31 +00003312 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
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003322 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
3323 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3324 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003325 }
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 }
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003338
Chris Lattner4333f8b2007-04-30 17:29:31 +00003339 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).
Chris Lattnerf852e332007-06-15 19:11:01 +00003353 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 }
Chris Lattner4333f8b2007-04-30 17:29:31 +00003360 }
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.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003370 for (unsigned i = RegStart; i != RegEnd; ++i)
3371 Regs.push_back(RegClassRegs[i]);
Chris Lattner4333f8b2007-04-30 17:29:31 +00003372
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003373 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
3374 OpInfo.ConstraintVT);
3375 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs);
3376 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003377 }
3378 }
3379
3380 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003381 return;
Chris Lattner4333f8b2007-04-30 17:29:31 +00003382}
3383
3384
Chris Lattner476e67b2006-01-26 22:24:51 +00003385/// visitInlineAsm - Handle a call to an InlineAsm object.
3386///
3387void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3388 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
Chris Lattner476e67b2006-01-26 22:24:51 +00003389
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003390 /// ConstraintOperands - Information about all of the constraints.
3391 std::vector<AsmOperandInfo> ConstraintOperands;
Chris Lattner476e67b2006-01-26 22:24:51 +00003392
3393 SDOperand Chain = getRoot();
3394 SDOperand Flag;
3395
Chris Lattner1558fc62006-02-01 18:59:47 +00003396 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00003397
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003398 // Do a prepass over the constraints, canonicalizing them, and building up the
3399 // ConstraintOperands list.
3400 std::vector<InlineAsm::ConstraintInfo>
3401 ConstraintInfos = IA->ParseConstraints();
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003402
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.
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003409 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3410 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
3411 AsmOperandInfo &OpInfo = ConstraintOperands.back();
3412
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003413 MVT::ValueType OpVT = MVT::Other;
3414
3415 // Compute the value type for each operand.
3416 switch (OpInfo.Type) {
Chris Lattner7ad77df2006-02-22 00:56:39 +00003417 case InlineAsm::isOutput:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003418 if (!OpInfo.isIndirect) {
3419 // The return value of the call is this value. As such, there is no
3420 // corresponding argument.
Chris Lattner7ad77df2006-02-22 00:56:39 +00003421 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3422 OpVT = TLI.getValueType(I.getType());
3423 } else {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003424 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner7ad77df2006-02-22 00:56:39 +00003425 }
3426 break;
3427 case InlineAsm::isInput:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003428 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner7ad77df2006-02-22 00:56:39 +00003429 break;
3430 case InlineAsm::isClobber:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003431 // Nothing to do.
Chris Lattner7ad77df2006-02-22 00:56:39 +00003432 break;
3433 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00003434
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003435 // 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();
Chris Lattner412d61a2007-04-29 18:58:03 +00003439 // 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 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003458 }
Chris Lattner412d61a2007-04-29 18:58:03 +00003459
3460 OpVT = TLI.getValueType(OpTy, true);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003461 }
3462
3463 OpInfo.ConstraintVT = OpVT;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003464
Chris Lattneref073322007-04-30 17:16:27 +00003465 // Compute the constraint code and ConstraintType to use.
3466 OpInfo.ComputeConstraintToUse(TLI);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003467
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003468 // Keep track of whether we see an earlyclobber.
3469 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner401d8db2007-04-28 21:12:06 +00003470
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
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003508 // 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);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003512 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003513 ConstraintInfos.clear();
3514
3515
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003516 // 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
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003527 // 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
Chris Lattner3a5ed552006-02-01 01:28:23 +00003533
Chris Lattner5c79f982006-02-21 23:12:12 +00003534 // Loop over all of the inputs, copying the operand values into the
3535 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00003536 RegsForValue RetValRegs;
Chris Lattner5c79f982006-02-21 23:12:12 +00003537
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003538 // 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];
Chris Lattner7ad77df2006-02-22 00:56:39 +00003543
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003544 switch (OpInfo.Type) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00003545 case InlineAsm::isOutput: {
Chris Lattnerde339fa2007-04-28 21:03:16 +00003546 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3547 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerd102ed02007-04-28 06:08:13 +00003548 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner401d8db2007-04-28 21:12:06 +00003549 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner9fed5b62006-02-27 23:45:39 +00003550
Chris Lattner9fed5b62006-02-27 23:45:39 +00003551 // Add information to the INLINEASM node to know about this output.
3552 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003553 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3554 TLI.getPointerTy()));
Chris Lattner401d8db2007-04-28 21:12:06 +00003555 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner9fed5b62006-02-27 23:45:39 +00003556 break;
3557 }
3558
Chris Lattnerb2e55562007-04-28 21:01:43 +00003559 // Otherwise, this is a register or register class output.
Chris Lattner9fed5b62006-02-27 23:45:39 +00003560
Chris Lattner6f87d182006-02-22 22:37:12 +00003561 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00003562 // we can use.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003563 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003564 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003565 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner968f8032006-10-31 07:33:13 +00003566 exit(1);
3567 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00003568
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003569 if (!OpInfo.isIndirect) {
3570 // This is the result value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00003571 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00003572 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00003573 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003574 RetValRegs = OpInfo.AssignedRegs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00003575 } else {
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003576 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003577 OpInfo.CallOperandVal));
Chris Lattner3a5ed552006-02-01 01:28:23 +00003578 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003579
3580 // Add information to the INLINEASM node to know that this register is
3581 // set.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003582 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3583 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003584 break;
3585 }
3586 case InlineAsm::isInput: {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003587 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner65ad53f2006-02-04 02:16:44 +00003588
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003589 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner7f5880b2006-02-02 00:25:23 +00003590 // If this is required to match an output register we have already set,
3591 // just use its register.
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003592 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00003593
Chris Lattner571d9642006-02-23 19:21:04 +00003594 // 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();
Chris Lattnerb0305322006-07-20 19:02:21 +00003601 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3602 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00003603 "Skipped past definitions?");
3604 CurOp += (NumOps>>3)+1;
3605 }
3606
3607 unsigned NumOps =
3608 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnere3eeb242007-02-01 01:21:12 +00003609 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 }
Chris Lattner571d9642006-02-23 19:21:04 +00003619
Chris Lattnere3eeb242007-02-01 01:21:12 +00003620 // Use the produced MatchedRegs object to
Dan Gohman78677932007-06-28 23:29:44 +00003621 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattnere3eeb242007-02-01 01:21:12 +00003622 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");
Chris Lattner571d9642006-02-23 19:21:04 +00003627 }
Chris Lattner7f5880b2006-02-02 00:25:23 +00003628 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003629
Chris Lattnerb2e55562007-04-28 21:01:43 +00003630 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003631 assert(!OpInfo.isIndirect &&
Chris Lattner1deacd62007-04-28 06:42:38 +00003632 "Don't know how to handle indirect other inputs yet!");
3633
Chris Lattnerd8c9cb92007-08-25 00:47:38 +00003634 std::vector<SDOperand> Ops;
3635 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
3636 Ops, DAG);
3637 if (Ops.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003638 cerr << "Invalid operand for inline asm constraint '"
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003639 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner6f043b92006-10-31 19:41:18 +00003640 exit(1);
3641 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003642
3643 // Add information to the INLINEASM node to know about this input.
Chris Lattnerd8c9cb92007-08-25 00:47:38 +00003644 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003645 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3646 TLI.getPointerTy()));
Chris Lattnerd8c9cb92007-08-25 00:47:38 +00003647 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner7ef7a642006-02-24 01:11:24 +00003648 break;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003649 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner401d8db2007-04-28 21:12:06 +00003650 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner1deacd62007-04-28 06:42:38 +00003651 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3652 "Memory operands expect pointer values");
3653
Chris Lattner7ef7a642006-02-24 01:11:24 +00003654 // Add information to the INLINEASM node to know about this input.
3655 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc7596ef2007-05-15 01:33:58 +00003656 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3657 TLI.getPointerTy()));
Chris Lattner7ef7a642006-02-24 01:11:24 +00003658 AsmNodeOperands.push_back(InOperandVal);
3659 break;
3660 }
3661
Chris Lattnerb2e55562007-04-28 21:01:43 +00003662 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3663 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3664 "Unknown constraint type!");
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003665 assert(!OpInfo.isIndirect &&
Chris Lattner1deacd62007-04-28 06:42:38 +00003666 "Don't know how to handle indirect register inputs yet!");
Chris Lattner7ef7a642006-02-24 01:11:24 +00003667
3668 // Copy the input into the appropriate registers.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003669 assert(!OpInfo.AssignedRegs.Regs.empty() &&
3670 "Couldn't allocate input reg!");
Chris Lattner7ef7a642006-02-24 01:11:24 +00003671
Dan Gohman78677932007-06-28 23:29:44 +00003672 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner7ef7a642006-02-24 01:11:24 +00003673
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003674 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
3675 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003676 break;
3677 }
Chris Lattner571d9642006-02-23 19:21:04 +00003678 case InlineAsm::isClobber: {
Chris Lattner571d9642006-02-23 19:21:04 +00003679 // Add the clobbered value to the operand list, so that the register
3680 // allocator is aware that the physreg got clobbered.
Chris Lattner8cfd33b2007-04-30 21:11:17 +00003681 if (!OpInfo.AssignedRegs.Regs.empty())
3682 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
3683 AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003684 break;
3685 }
Chris Lattner571d9642006-02-23 19:21:04 +00003686 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003687 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003688
3689 // Finish up input operands.
3690 AsmNodeOperands[0] = Chain;
3691 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3692
Chris Lattnerbd887772006-08-14 23:53:35 +00003693 Chain = DAG.getNode(ISD::INLINEASM,
3694 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003695 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003696 Flag = Chain.getValue(1);
3697
Chris Lattner2e56e892006-01-31 02:03:41 +00003698 // If this asm returns a register value, copy the result from that register
3699 // and set it as the value of the call.
Chris Lattner51114992007-04-12 06:00:20 +00003700 if (!RetValRegs.Regs.empty()) {
Dan Gohman78677932007-06-28 23:29:44 +00003701 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner51114992007-04-12 06:00:20 +00003702
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
Dan Gohmana8665142007-06-25 16:23:39 +00003705 // bit_convert.
3706 if (MVT::isVector(Val.getValueType())) {
Chris Lattner51114992007-04-12 06:00:20 +00003707 const VectorType *VTy = cast<VectorType>(I.getType());
Dan Gohmana8665142007-06-25 16:23:39 +00003708 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
Chris Lattner51114992007-04-12 06:00:20 +00003709
Dan Gohmana8665142007-06-25 16:23:39 +00003710 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
Chris Lattner51114992007-04-12 06:00:20 +00003711 }
3712
3713 setValue(&I, Val);
3714 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003715
Chris Lattner2e56e892006-01-31 02:03:41 +00003716 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) {
Chris Lattner6f87d182006-02-22 22:37:12 +00003721 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00003722 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohman78677932007-06-28 23:29:44 +00003723 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner6f87d182006-02-22 22:37:12 +00003724 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00003725 }
3726
3727 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003728 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00003729 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003730 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00003731 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00003732 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00003733 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003734 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3735 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003736 DAG.setRoot(Chain);
3737}
3738
3739
Chris Lattner7a60d912005-01-07 07:47:53 +00003740void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3741 SDOperand Src = getValue(I.getOperand(0));
3742
3743 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00003744
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);
Chris Lattner7a60d912005-01-07 07:47:53 +00003749
3750 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00003751 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00003752 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3753 Src, getIntPtrConstant(ElementSize));
3754
Reid Spencere63b6512006-12-31 05:55:36 +00003755 TargetLowering::ArgListTy Args;
3756 TargetLowering::ArgListEntry Entry;
3757 Entry.Node = Src;
3758 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003759 Args.push_back(Entry);
Chris Lattner1f45cd72005-01-08 19:26:18 +00003760
3761 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003762 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003763 DAG.getExternalSymbol("malloc", IntPtr),
3764 Args, DAG);
3765 setValue(&I, Result.first); // Pointers always fit in registers
3766 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003767}
3768
3769void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencere63b6512006-12-31 05:55:36 +00003770 TargetLowering::ArgListTy Args;
3771 TargetLowering::ArgListEntry Entry;
3772 Entry.Node = getValue(I.getOperand(0));
3773 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003774 Args.push_back(Entry);
Chris Lattner7a60d912005-01-07 07:47:53 +00003775 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00003776 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003777 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003778 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3779 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003780}
3781
Chris Lattner13d7c252005-08-26 20:54:47 +00003782// 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) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003789 cerr << "If a target marks an instruction with "
3790 << "'usesCustomDAGSchedInserter', it must implement "
3791 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner13d7c252005-08-26 20:54:47 +00003792 abort();
3793 return 0;
3794}
3795
Chris Lattner58cfd792005-01-09 00:00:49 +00003796void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003797 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3798 getValue(I.getOperand(1)),
3799 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00003800}
3801
3802void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003803 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));
Chris Lattner7a60d912005-01-07 07:47:53 +00003808}
3809
3810void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003811 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3812 getValue(I.getOperand(1)),
3813 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003814}
3815
3816void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003817 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))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003822}
3823
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003824/// TargetLowering::LowerArguments - This is the default LowerArguments
3825/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00003826/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3827/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003828std::vector<SDOperand>
3829TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003830 const FunctionType *FTy = F.getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +00003831 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003832 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3833 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00003834 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003835 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;
Anton Korobeynikov06f7d4b2007-01-28 18:01:49 +00003840 unsigned j = 1;
Anton Korobeynikov9fa38392007-01-28 16:04:40 +00003841 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3842 I != E; ++I, ++j) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003843 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003844 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003845 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003846 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003847
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003848 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3849 // that is zero extended!
Reid Spencera472f662007-04-11 02:44:20 +00003850 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003851 Flags &= ~(ISD::ParamFlags::SExt);
Reid Spencera472f662007-04-11 02:44:20 +00003852 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003853 Flags |= ISD::ParamFlags::SExt;
Reid Spencera472f662007-04-11 02:44:20 +00003854 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003855 Flags |= ISD::ParamFlags::InReg;
Reid Spencera472f662007-04-11 02:44:20 +00003856 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003857 Flags |= ISD::ParamFlags::StructReturn;
Rafael Espindola66011c12007-08-10 14:44:42 +00003858 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ByVal)) {
Rafael Espindolab567e3f2007-07-06 10:57:03 +00003859 Flags |= ISD::ParamFlags::ByVal;
Rafael Espindola66011c12007-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 Sands644f9172007-07-27 12:58:54 +00003867 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::Nest))
3868 Flags |= ISD::ParamFlags::Nest;
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003869 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003870
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003871 switch (getTypeAction(VT)) {
3872 default: assert(0 && "Unknown type action!");
3873 case Legal:
3874 RetVals.push_back(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003875 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003876 break;
3877 case Promote:
3878 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003879 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003880 break;
Dan Gohman78677932007-06-28 23:29:44 +00003881 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));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003893 }
3894 break;
3895 }
Dan Gohman78677932007-06-28 23:29:44 +00003896 }
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003897 }
Evan Cheng9618df12006-04-25 23:03:35 +00003898
Chris Lattner3d826992006-05-16 06:45:34 +00003899 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003900
3901 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00003902 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3903 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003904 &Ops[0], Ops.size()).Val;
Dan Gohman533dd162007-07-02 16:18:06 +00003905 unsigned NumArgRegs = Result->getNumValues() - 1;
3906 DAG.setRoot(SDOperand(Result, NumArgRegs));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003907
3908 // Set up the return result vector.
3909 Ops.clear();
3910 unsigned i = 0;
Reid Spencere63b6512006-12-31 05:55:36 +00003911 unsigned Idx = 1;
3912 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3913 ++I, ++Idx) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003914 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)) {
Reid Spencera472f662007-04-11 02:44:20 +00003924 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
Chris Lattner96035be2007-01-04 22:22:37 +00003925 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3926 DAG.getValueType(VT));
Reid Spencera472f662007-04-11 02:44:20 +00003927 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
Chris Lattner96035be2007-01-04 22:22:37 +00003928 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3929 DAG.getValueType(VT));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003930 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 }
Dan Gohman533dd162007-07-02 16:18:06 +00003938 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++);
Dan Gohmanf8f531b2007-07-09 20:59:04 +00003944 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003945 break;
3946 }
Dan Gohman533dd162007-07-02 16:18:06 +00003947 }
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003948 }
Dan Gohman533dd162007-07-02 16:18:06 +00003949 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003950 return Ops;
3951}
3952
Chris Lattneraaa23d92006-05-16 22:53:20 +00003953
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>
Reid Spencere63b6512006-12-31 05:55:36 +00003959TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3960 bool RetTyIsSigned, bool isVarArg,
Chris Lattneraaa23d92006-05-16 22:53:20 +00003961 unsigned CallingConv, bool isTailCall,
3962 SDOperand Callee,
3963 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00003964 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003965 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) {
Reid Spencere63b6512006-12-31 05:55:36 +00003973 MVT::ValueType VT = getValueType(Args[i].Ty);
3974 SDOperand Op = Args[i].Node;
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003975 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003976 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003977 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003978
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003979 if (Args[i].isSExt)
3980 Flags |= ISD::ParamFlags::SExt;
3981 if (Args[i].isZExt)
3982 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003983 if (Args[i].isInReg)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003984 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003985 if (Args[i].isSRet)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003986 Flags |= ISD::ParamFlags::StructReturn;
Rafael Espindola9c3d20d2007-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 Sands644f9172007-07-27 12:58:54 +00003996 if (Args[i].isNest)
3997 Flags |= ISD::ParamFlags::Nest;
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003998 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003999
Chris Lattneraaa23d92006-05-16 22:53:20 +00004000 switch (getTypeAction(VT)) {
4001 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00004002 case Legal:
Chris Lattneraaa23d92006-05-16 22:53:20 +00004003 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00004004 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00004005 break;
4006 case Promote:
4007 if (MVT::isInteger(VT)) {
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00004008 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;
Chris Lattneraaa23d92006-05-16 22:53:20 +00004015 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
4016 } else {
4017 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
Dale Johannesena2b3c172007-07-03 00:53:03 +00004018 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004019 }
4020 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00004021 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00004022 break;
Dan Gohman533dd162007-07-02 16:18:06 +00004023 case Expand: {
4024 MVT::ValueType PartVT = getRegisterType(VT);
4025 unsigned NumParts = getNumRegisters(VT);
4026 SmallVector<SDOperand, 4> Parts(NumParts);
Dan Gohmanf8f531b2007-07-09 20:59:04 +00004027 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT);
Dan Gohman533dd162007-07-02 16:18:06 +00004028 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));
Chris Lattneraaa23d92006-05-16 22:53:20 +00004037 }
4038 break;
4039 }
Dan Gohman533dd162007-07-02 16:18:06 +00004040 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00004041 }
4042
4043 // Figure out the result value types.
Dan Gohman78677932007-06-28 23:29:44 +00004044 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;
Chris Lattneraaa23d92006-05-16 22:53:20 +00004050
4051 RetTys.push_back(MVT::Other); // Always has a chain.
4052
Dan Gohman78677932007-06-28 23:29:44 +00004053 // Create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00004054 SDOperand Res = DAG.getNode(ISD::CALL,
Dan Gohman78677932007-06-28 23:29:44 +00004055 DAG.getVTList(&RetTys[0], NumRegs + 1),
Chris Lattner65879ca2006-08-16 22:57:46 +00004056 &Ops[0], Ops.size());
Chris Lattner3ffe7182007-08-02 18:08:16 +00004057 Chain = Res.getValue(NumRegs);
Dan Gohman78677932007-06-28 23:29:44 +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);
Dan Gohmanf8f531b2007-07-09 20:59:04 +00004067 Res = getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT, AssertOp);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004068 }
Dan Gohman78677932007-06-28 23:29:44 +00004069
4070 return std::make_pair(Res, Chain);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004071}
4072
Chris Lattner29dcc712005-05-14 05:50:48 +00004073SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00004074 assert(0 && "LowerOperation not implemented for this target!");
4075 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00004076 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00004077}
4078
Nate Begeman595ec732006-01-28 03:14:31 +00004079SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4080 SelectionDAG &DAG) {
4081 assert(0 && "CustomPromoteOperation not implemented for this target!");
4082 abort();
4083 return SDOperand();
4084}
4085
Evan Cheng6781b6e2006-02-15 21:59:04 +00004086/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00004087/// operand.
4088static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00004089 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004090 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);
Evan Cheng81fcea82006-02-14 08:22:34 +00004098 }
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);
Evan Cheng81fcea82006-02-14 08:22:34 +00004110 }
4111
4112 return Value;
4113 }
4114}
4115
Evan Cheng6781b6e2006-02-15 21:59:04 +00004116/// 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) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00004122 uint64_t Val = 0;
Dan Gohman1796f1f2007-05-18 17:52:13 +00004123 unsigned MSB = MVT::getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004124 if (TLI.isLittleEndian())
4125 Offset = Offset + MSB - 1;
4126 for (unsigned i = 0; i != MSB; ++i) {
Evan Cheng6e12a052006-11-29 01:38:07 +00004127 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng6781b6e2006-02-15 21:59:04 +00004128 Offset += TLI.isLittleEndian() ? -1 : 1;
4129 }
4130 return DAG.getConstant(Val, VT);
4131}
4132
Evan Cheng81fcea82006-02-14 08:22:34 +00004133/// 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
Evan Chengdb2a7a72006-02-14 20:12:38 +00004140/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00004141/// 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.
Evan Chengdb2a7a72006-02-14 20:12:38 +00004143static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4144 unsigned Limit, uint64_t Size,
4145 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004146 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
Evan Chengd5026102006-02-14 09:11:59 +00004167 MVT::ValueType LVT = MVT::i64;
4168 while (!TLI.isTypeLegal(LVT))
4169 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4170 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00004171
Evan Chengd5026102006-02-14 09:11:59 +00004172 if (VT > LVT)
4173 VT = LVT;
4174
Evan Cheng04514992006-02-14 23:05:54 +00004175 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00004176 while (Size != 0) {
Dan Gohman1796f1f2007-05-18 17:52:13 +00004177 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng81fcea82006-02-14 08:22:34 +00004178 while (VTSize > Size) {
4179 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004180 VTSize >>= 1;
4181 }
Evan Chengd5026102006-02-14 09:11:59 +00004182 assert(MVT::isInteger(VT));
4183
4184 if (++NumMemOps > Limit)
4185 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00004186 MemOps.push_back(VT);
4187 Size -= VTSize;
4188 }
Evan Chengd5026102006-02-14 09:11:59 +00004189
4190 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00004191}
4192
Chris Lattner875def92005-01-11 05:56:49 +00004193void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004194 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 Gohman8dc0b932007-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
Evan Cheng81fcea82006-02-14 08:22:34 +00004212 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4213 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00004214
4215 // Expand memset / memcpy to a series of load / store ops
4216 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004217 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00004218 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00004219 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00004220 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00004221 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4222 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00004223 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00004224 unsigned Offset = 0;
4225 for (unsigned i = 0; i < NumMemOps; i++) {
4226 MVT::ValueType VT = MemOps[i];
Dan Gohman1796f1f2007-05-18 17:52:13 +00004227 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00004228 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00004229 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00004230 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004231 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00004232 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00004233 Offset += VTSize;
4234 }
Evan Cheng81fcea82006-02-14 08:22:34 +00004235 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004236 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00004237 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004238 case ISD::MEMCPY: {
4239 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4240 Size->getValue(), Align, TLI)) {
4241 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004242 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004243 GlobalAddressSDNode *G = NULL;
4244 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004245 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004246
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));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004253 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00004254 }
4255 if (G) {
4256 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengfeba5072006-11-29 01:58:12 +00004257 if (GV && GV->isConstant()) {
Evan Cheng38280c02006-03-10 23:52:03 +00004258 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004259 if (!Str.empty()) {
4260 CopyFromStr = true;
4261 SrcOff += SrcDelta;
4262 }
4263 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00004264 }
4265
Evan Chenge2038bd2006-02-15 01:54:51 +00004266 for (unsigned i = 0; i < NumMemOps; i++) {
4267 MVT::ValueType VT = MemOps[i];
Dan Gohman1796f1f2007-05-18 17:52:13 +00004268 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004269 SDOperand Value, Chain, Store;
4270
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004271 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00004272 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4273 Chain = getRoot();
4274 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00004275 DAG.getStore(Chain, Value,
4276 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004277 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004278 } else {
4279 Value = DAG.getLoad(VT, getRoot(),
4280 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00004281 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004282 Chain = Value.getValue(1);
4283 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00004284 DAG.getStore(Chain, Value,
4285 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004286 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004287 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004288 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004289 SrcOff += VTSize;
4290 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00004291 }
4292 }
4293 break;
4294 }
4295 }
4296
4297 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004298 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4299 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00004300 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00004301 }
4302 }
4303
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004304 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00004305}
4306
Chris Lattner875def92005-01-11 05:56:49 +00004307//===----------------------------------------------------------------------===//
4308// SelectionDAGISel code
4309//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00004310
4311unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4312 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4313}
4314
Chris Lattnerc9950c12005-08-17 06:37:43 +00004315void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004316 AU.addRequired<AliasAnalysis>();
Chris Lattnerf6a6d3c2007-03-31 04:18:03 +00004317 AU.setPreservesAll();
Chris Lattnerc9950c12005-08-17 06:37:43 +00004318}
Chris Lattner7a60d912005-01-07 07:47:53 +00004319
Chris Lattner35397782005-12-05 07:10:48 +00004320
Chris Lattnerbba52192006-10-28 19:22:10 +00004321
Chris Lattner7a60d912005-01-07 07:47:53 +00004322bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman8dc0b932007-08-27 16:26:13 +00004323 // Get alias analysis for load/store combining.
4324 AA = &getAnalysis<AliasAnalysis>();
4325
Chris Lattner7a60d912005-01-07 07:47:53 +00004326 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4327 RegMap = MF.getSSARegMap();
Bill Wendling22e978a2006-12-07 20:04:42 +00004328 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004329
4330 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4331
Duncan Sands74137362007-06-13 16:53:21 +00004332 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();
Duncan Sands61166502007-06-06 10:05:18 +00004337
4338 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +00004339 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00004340
Evan Cheng276b44b2007-02-10 02:43:39 +00004341 // 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
Duncan Sands92bf2c62007-06-15 19:04:19 +00004349#ifndef NDEBUG
4350 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4351 "Not all catch info was assigned to a landing pad!");
4352#endif
4353
Chris Lattner7a60d912005-01-07 07:47:53 +00004354 return true;
4355}
4356
Chris Lattnered0110b2006-10-27 21:36:01 +00004357SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4358 unsigned Reg) {
4359 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00004360 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00004361 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00004362 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00004363
Chris Lattner33182322005-08-16 21:55:35 +00004364 MVT::ValueType SrcVT = Op.getValueType();
Dan Gohman78677932007-06-28 23:29:44 +00004365 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.
Dan Gohmanf8f531b2007-07-09 20:59:04 +00004371 getCopyToParts(DAG, Op, &Regs[0], NumRegs, RegisterVT);
Dan Gohman533dd162007-07-02 16:18:06 +00004372 for (unsigned i = 0; i != NumRegs; ++i)
Dan Gohman78677932007-06-28 23:29:44 +00004373 Chains[i] = DAG.getCopyToReg(getRoot(), Reg + i, Regs[i]);
4374 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattner7a60d912005-01-07 07:47:53 +00004375}
4376
Chris Lattner16f64df2005-01-17 17:15:02 +00004377void SelectionDAGISel::
Evan Chengde608342007-02-10 01:08:18 +00004378LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner16f64df2005-01-17 17:15:02 +00004379 std::vector<SDOperand> &UnorderedChains) {
4380 // If this is the entry block, emit arguments.
Evan Chengde608342007-02-10 01:08:18 +00004381 Function &F = *LLVMBB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004382 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00004383 SDOperand OldRoot = SDL.DAG.getRoot();
4384 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00004385
Chris Lattner6871b232005-10-30 19:42:35 +00004386 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]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00004391
Chris Lattner6871b232005-10-30 19:42:35 +00004392 // 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.
Chris Lattner8c504cf2007-02-25 18:40:32 +00004394 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4395 if (VMI != FuncInfo.ValueMap.end()) {
4396 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattner6871b232005-10-30 19:42:35 +00004397 UnorderedChains.push_back(Copy);
4398 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004399 }
Chris Lattner6871b232005-10-30 19:42:35 +00004400
Chris Lattner6871b232005-10-30 19:42:35 +00004401 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00004402 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00004403 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00004404}
4405
Duncan Sands92bf2c62007-06-15 19:04:19 +00004406static 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)
Duncan Sandsfe806382007-07-04 20:52:51 +00004411 if (isSelector(I)) {
Duncan Sands92bf2c62007-06-15 19:04:19 +00004412 // 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
Chris Lattner7a60d912005-01-07 07:47:53 +00004420void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4421 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00004422 FunctionLoweringInfo &FuncInfo) {
Dan Gohman8dc0b932007-08-27 16:26:13 +00004423 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00004424
4425 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00004426
Chris Lattner6871b232005-10-30 19:42:35 +00004427 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00004428 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattner6871b232005-10-30 19:42:35 +00004429 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00004430
4431 BB = FuncInfo.MBBMap[LLVMBB];
4432 SDL.setCurrentBasicBlock(BB);
4433
Duncan Sands92bf2c62007-06-15 19:04:19 +00004434 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands61166502007-06-06 10:05:18 +00004435
Duncan Sands92bf2c62007-06-15 19:04:19 +00004436 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
Evan Cheng77f541d2007-06-27 18:45:32 +00004443 // 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
Duncan Sands92bf2c62007-06-15 19:04:19 +00004451 // 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
Duncan Sandsfe806382007-07-04 20:52:51 +00004455 // 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.
Duncan Sands92bf2c62007-06-15 19:04:19 +00004462 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)
Duncan Sandsfe806382007-07-04 20:52:51 +00004467 if (isSelector(I))
Duncan Sands92bf2c62007-06-15 19:04:19 +00004468 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);
Duncan Sands61166502007-06-06 10:05:18 +00004473 }
4474 }
4475
Chris Lattner7a60d912005-01-07 07:47:53 +00004476 // 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);
Duncan Sands97f72362007-06-13 05:51:31 +00004480
Chris Lattner7a60d912005-01-07 07:47:53 +00004481 // Ensure that all instructions which are used outside of their defining
Duncan Sands97f72362007-06-13 05:51:31 +00004482 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner7a60d912005-01-07 07:47:53 +00004483 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sands97f72362007-06-13 05:51:31 +00004484 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner289aa442007-02-04 01:35:11 +00004485 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00004486 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00004487 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00004488 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00004489 }
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.
Misha Brukman835702a2005-04-21 22:36:52 +00004497 //
Chris Lattner84a03502006-10-27 23:50:33 +00004498 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00004499
4500 // Emit constants only once even if used by multiple PHI nodes.
4501 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00004502
Chris Lattner84a03502006-10-27 23:50:33 +00004503 // 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
Dan Gohmanf8f531b2007-07-09 20:59:04 +00004508 // Check successor nodes' PHI nodes that expect a constant to be available
4509 // from this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00004510 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4511 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00004512 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00004513 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00004514
Chris Lattner84a03502006-10-27 23:50:33 +00004515 // 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();
Chris Lattner7a60d912005-01-07 07:47:53 +00004522 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();
Chris Lattner84a03502006-10-27 23:50:33 +00004528 (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);
Chris Lattner90f42382006-11-29 01:12:32 +00004534
Chris Lattner84a03502006-10-27 23:50:33 +00004535 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));
Chris Lattner7a60d912005-01-07 07:47:53 +00004541 }
Chris Lattner84a03502006-10-27 23:50:33 +00004542 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));
Chris Lattnerba380352006-03-31 02:12:18 +00004552 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004553 }
Chris Lattner84a03502006-10-27 23:50:33 +00004554
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());
Dan Gohmana8665142007-06-25 16:23:39 +00004558 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman04deef32007-06-21 14:42:22 +00004559 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner84a03502006-10-27 23:50:33 +00004560 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4561 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004562 }
4563 ConstantsOut.clear();
4564
Chris Lattner718b5c22005-01-13 17:59:43 +00004565 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00004566 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00004567 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 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004579 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4580 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00004581 }
4582
Chris Lattner7a60d912005-01-07 07:47:53 +00004583 // Lower the terminator after the copies are emitted.
Duncan Sands97f72362007-06-13 05:51:31 +00004584 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00004585
Nate Begemaned728c12006-03-27 01:32:24 +00004586 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004587 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00004588 SwitchCases.clear();
4589 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +00004590 JTCases.clear();
4591 JTCases = SDL.JTCases;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004592 BitTestCases.clear();
4593 BitTestCases = SDL.BitTestCases;
4594
Chris Lattner4108bb02005-01-17 19:43:36 +00004595 // Make sure the root of the DAG is up-to-date.
4596 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00004597}
4598
Nate Begemaned728c12006-03-27 01:32:24 +00004599void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004600 // Run the DAG combiner in pre-legalize mode.
Dan Gohman8dc0b932007-08-27 16:26:13 +00004601 DAG.Combine(false, *AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004602
Bill Wendling22e978a2006-12-07 20:04:42 +00004603 DOUT << "Lowered selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004604 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004605
Chris Lattner7a60d912005-01-07 07:47:53 +00004606 // Second step, hack on the DAG until it only uses operations and types that
4607 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004608 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004609
Bill Wendling22e978a2006-12-07 20:04:42 +00004610 DOUT << "Legalized selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004611 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004612
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004613 // Run the DAG combiner in post-legalize mode.
Dan Gohman8dc0b932007-08-27 16:26:13 +00004614 DAG.Combine(true, *AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004615
Evan Cheng739a6a42006-01-21 02:32:06 +00004616 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004617
Chris Lattner5ca31d92005-03-30 01:10:47 +00004618 // Third, instruction select all of the operations to machine code, adding the
4619 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004620 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004621
Bill Wendling22e978a2006-12-07 20:04:42 +00004622 DOUT << "Selected machine code:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004623 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004624}
Chris Lattner7a60d912005-01-07 07:47:53 +00004625
Nate Begemaned728c12006-03-27 01:32:24 +00004626void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4627 FunctionLoweringInfo &FuncInfo) {
4628 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4629 {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004630 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004631 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 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004640
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";);
Nate Begemaned728c12006-03-27 01:32:24 +00004646
Chris Lattner5ca31d92005-03-30 01:10:47 +00004647 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004648 // PHI nodes in successors.
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004649 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00004650 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!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004654 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004655 PHI->addMachineBasicBlockOperand(BB);
4656 }
4657 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004658 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004659
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 Gohman8dc0b932007-08-27 16:26:13 +00004665 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +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 Gohman8dc0b932007-08-27 16:26:13 +00004678 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +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);
Anton Korobeynikove2880402007-04-13 06:53:51 +00004708 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004709 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
Nate Begeman866b4b42006-04-23 06:26:20 +00004723 // 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
Anton Korobeynikov70378262007-03-25 15:07:15 +00004726 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 Gohman8dc0b932007-08-27 16:26:13 +00004731 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo);
Anton Korobeynikov70378262007-03-25 15:07:15 +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);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004739 }
Anton Korobeynikov70378262007-03-25 15:07:15 +00004740
4741 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4742 CurDAG = &JSDAG;
Dan Gohman8dc0b932007-08-27 16:26:13 +00004743 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004744 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov70378262007-03-25 15:07:15 +00004745 BB = JTCases[i].second.MBB;
4746 JSDL.setCurrentBasicBlock(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004747 // Emit the code
Anton Korobeynikov70378262007-03-25 15:07:15 +00004748 JSDL.visitJumpTable(JTCases[i].second);
4749 JSDAG.setRoot(JSDL.getRoot());
4750 CodeGenAndEmitDAG(JSDAG);
4751
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004752 // 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!");
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004758 // "default" BB. We can go there only from header BB.
Anton Korobeynikov70378262007-03-25 15:07:15 +00004759 if (PHIBB == JTCases[i].second.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004760 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov70378262007-03-25 15:07:15 +00004761 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemandf488392006-05-03 03:48:02 +00004762 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004763 // JT BB. Just iterate over successors here
Nate Begemandf488392006-05-03 03:48:02 +00004764 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004765 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004766 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004767 }
4768 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004769 }
4770
Chris Lattner76a7bc82006-10-22 23:00:53 +00004771 // 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
Nate Begemaned728c12006-03-27 01:32:24 +00004783 // If we generated any switch lowering information, build and codegen any
4784 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004785 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004786 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004787 CurDAG = &SDAG;
Dan Gohman8dc0b932007-08-27 16:26:13 +00004788 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004789
Nate Begemaned728c12006-03-27 01:32:24 +00004790 // Set the current basic block to the mbb we wish to insert the code into
4791 BB = SwitchCases[i].ThisBB;
4792 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004793
Nate Begemaned728c12006-03-27 01:32:24 +00004794 // Emit the code
4795 SDL.visitSwitchCase(SwitchCases[i]);
4796 SDAG.setRoot(SDL.getRoot());
4797 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004798
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.
Chris Lattner963ddad2006-10-24 17:57:59 +00004803 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004804 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 }
Nate Begemaned728c12006-03-27 01:32:24 +00004815 }
Chris Lattner707339a52006-09-07 01:59:34 +00004816
4817 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004818 if (BB == SwitchCases[i].FalseBB)
4819 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004820
4821 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004822 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004823 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004824 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004825 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004826 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004827}
Evan Cheng739a6a42006-01-21 02:32:06 +00004828
Jim Laskey95eda5b2006-08-01 14:21:23 +00004829
Evan Cheng739a6a42006-01-21 02:32:06 +00004830//===----------------------------------------------------------------------===//
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();
Evan Chengc1e1d972006-01-23 07:01:07 +00004835
Jim Laskey29e635d2006-08-02 12:30:23 +00004836 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004837
4838 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004839 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004840 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004841 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004842
Jim Laskey03593f72006-08-01 18:29:48 +00004843 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004844 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004845 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004846}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004847
Chris Lattner47639db2006-03-06 00:22:00 +00004848
Jim Laskey03593f72006-08-01 18:29:48 +00004849HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4850 return new HazardRecognizer();
4851}
4852
Chris Lattner6df34962006-10-11 03:58:02 +00004853//===----------------------------------------------------------------------===//
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 Gohmanf0bb1282007-07-24 23:00:27 +00004863 int64_t DesiredMaskS) const {
Chris Lattner6df34962006-10-11 03:58:02 +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;
Dan Gohman309d3d52007-06-22 14:59:07 +00004878 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner6df34962006-10-11 03:58:02 +00004879 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 Gohmanf0bb1282007-07-24 23:00:27 +00004892 int64_t DesiredMaskS) const {
Chris Lattner6df34962006-10-11 03:58:02 +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;
Dan Gohman309d3d52007-06-22 14:59:07 +00004909 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner6df34962006-10-11 03:58:02 +00004910
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
Jim Laskey03593f72006-08-01 18:29:48 +00004921
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004922/// 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
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004932 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)) {
Bill Wendling22e978a2006-12-07 20:04:42 +00004947 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004948 exit(1);
4949 }
4950
4951 // Add this to the output node.
Chris Lattnerb49917d2007-04-09 00:33:58 +00004952 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner9bd5ed62006-12-16 21:14:48 +00004953 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattnerb49917d2007-04-09 00:33:58 +00004954 IntPtrTy));
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004955 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}
Devang Patel09f162c2007-05-01 21:15:47 +00004964
Devang Patel8c78a0b2007-05-03 01:11:54 +00004965char SelectionDAGISel::ID = 0;