blob: 4f4c2cba00ada1aa2b31694bd0efae2dbebf2dae [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> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000076 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000077 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000078 cl::desc("Instruction schedulers available:"));
79
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 {
Chris Lattner6f87d182006-02-22 22:37:12 +000093 /// Regs - This list hold the register (for legal and promoted values)
94 /// or register set (for expanded values) that the value should be assigned
95 /// to.
96 std::vector<unsigned> Regs;
97
98 /// RegVT - The value type of each register.
99 ///
100 MVT::ValueType RegVT;
101
102 /// ValueVT - The value type of the LLVM value, which may be promoted from
103 /// RegVT or made from merging the two expanded parts.
104 MVT::ValueType ValueVT;
105
106 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
107
108 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
109 : RegVT(regvt), ValueVT(valuevt) {
110 Regs.push_back(Reg);
111 }
112 RegsForValue(const std::vector<unsigned> &regs,
113 MVT::ValueType regvt, MVT::ValueType valuevt)
114 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
115 }
116
117 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
118 /// this value and returns the result as a ValueVT value. This uses
119 /// Chain/Flag as the input and updates them for the output Chain/Flag.
120 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000121 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000122
123 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
124 /// specified value into the registers specified by this object. This uses
125 /// Chain/Flag as the input and updates them for the output Chain/Flag.
126 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000127 SDOperand &Chain, SDOperand &Flag,
128 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000129
130 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
131 /// operand list. This adds the code marker and includes the number of
132 /// values added into it.
133 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000134 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000135 };
136}
Evan Chengc1e1d972006-01-23 07:01:07 +0000137
Chris Lattner7a60d912005-01-07 07:47:53 +0000138namespace llvm {
139 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000140 /// createDefaultScheduler - This creates an instruction scheduler appropriate
141 /// for the target.
142 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
143 SelectionDAG *DAG,
144 MachineBasicBlock *BB) {
145 TargetLowering &TLI = IS->getTargetLowering();
146
147 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
148 return createTDListDAGScheduler(IS, DAG, BB);
149 } else {
150 assert(TLI.getSchedulingPreference() ==
151 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
152 return createBURRListDAGScheduler(IS, DAG, BB);
153 }
154 }
155
156
157 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000158 /// FunctionLoweringInfo - This contains information that is global to a
159 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000160 class FunctionLoweringInfo {
161 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000162 TargetLowering &TLI;
163 Function &Fn;
164 MachineFunction &MF;
165 SSARegMap *RegMap;
166
167 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
168
169 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
170 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
171
172 /// ValueMap - Since we emit code for the function a basic block at a time,
173 /// we must remember which virtual registers hold the values for
174 /// cross-basic-block values.
Chris Lattner289aa442007-02-04 01:35:11 +0000175 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000176
177 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
178 /// the entry block. This allows the allocas to be efficiently referenced
179 /// anywhere in the function.
180 std::map<const AllocaInst*, int> StaticAllocaMap;
181
182 unsigned MakeReg(MVT::ValueType VT) {
183 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
184 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000185
186 /// isExportedInst - Return true if the specified value is an instruction
187 /// exported from its block.
188 bool isExportedInst(const Value *V) {
189 return ValueMap.count(V);
190 }
Misha Brukman835702a2005-04-21 22:36:52 +0000191
Chris Lattner49409cb2006-03-16 19:51:18 +0000192 unsigned CreateRegForValue(const Value *V);
193
Chris Lattner7a60d912005-01-07 07:47:53 +0000194 unsigned InitializeRegForValue(const Value *V) {
195 unsigned &R = ValueMap[V];
196 assert(R == 0 && "Already initialized this value register!");
197 return R = CreateRegForValue(V);
198 }
199 };
200}
201
202/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000203/// PHI nodes or outside of the basic block that defines it, or used by a
204/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000205static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
206 if (isa<PHINode>(I)) return true;
207 BasicBlock *BB = I->getParent();
208 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000209 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000210 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000211 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000212 return true;
213 return false;
214}
215
Chris Lattner6871b232005-10-30 19:42:35 +0000216/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000217/// entry block, return true. This includes arguments used by switches, since
218/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000219static bool isOnlyUsedInEntryBlock(Argument *A) {
220 BasicBlock *Entry = A->getParent()->begin();
221 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000222 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000223 return false; // Use not in entry block.
224 return true;
225}
226
Chris Lattner7a60d912005-01-07 07:47:53 +0000227FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000228 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000229 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
230
Chris Lattner6871b232005-10-30 19:42:35 +0000231 // Create a vreg for each argument register that is not dead and is used
232 // outside of the entry block for the function.
233 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
234 AI != E; ++AI)
235 if (!isOnlyUsedInEntryBlock(AI))
236 InitializeRegForValue(AI);
237
Chris Lattner7a60d912005-01-07 07:47:53 +0000238 // Initialize the mapping of values to registers. This is only set up for
239 // instruction values that are used outside of the block that defines
240 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000241 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000242 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
243 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000244 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000245 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000246 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000247 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +0000248 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000249 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000250
Reid Spencere0fc4df2006-10-20 07:07:24 +0000251 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000252 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000253 StaticAllocaMap[AI] =
Chris Lattnercb0ed0c2007-04-25 04:08:28 +0000254 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000255 }
256
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000257 for (; BB != EB; ++BB)
258 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000259 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
260 if (!isa<AllocaInst>(I) ||
261 !StaticAllocaMap.count(cast<AllocaInst>(I)))
262 InitializeRegForValue(I);
263
264 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
265 // also creates the initial PHI MachineInstrs, though none of the input
266 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000267 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000268 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
269 MBBMap[BB] = MBB;
270 MF.getBasicBlockList().push_back(MBB);
271
272 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
273 // appropriate.
274 PHINode *PN;
Chris Lattner84a03502006-10-27 23:50:33 +0000275 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
276 if (PN->use_empty()) continue;
277
278 MVT::ValueType VT = TLI.getValueType(PN->getType());
279 unsigned NumElements;
280 if (VT != MVT::Vector)
281 NumElements = TLI.getNumElements(VT);
282 else {
283 MVT::ValueType VT1,VT2;
284 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +0000285 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +0000286 VT1, VT2);
Chris Lattner8ea875f2005-01-07 21:34:19 +0000287 }
Chris Lattner84a03502006-10-27 23:50:33 +0000288 unsigned PHIReg = ValueMap[PN];
289 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Cheng20350c42006-11-27 23:37:22 +0000290 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner84a03502006-10-27 23:50:33 +0000291 for (unsigned i = 0; i != NumElements; ++i)
Evan Cheng20350c42006-11-27 23:37:22 +0000292 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner84a03502006-10-27 23:50:33 +0000293 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000294 }
295}
296
Chris Lattner49409cb2006-03-16 19:51:18 +0000297/// CreateRegForValue - Allocate the appropriate number of virtual registers of
298/// the correctly promoted or expanded types. Assign these registers
299/// consecutive vreg numbers and return the first assigned number.
300unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
301 MVT::ValueType VT = TLI.getValueType(V->getType());
302
303 // The number of multiples of registers that we need, to, e.g., split up
304 // a <2 x int64> -> 4 x i32 registers.
305 unsigned NumVectorRegs = 1;
306
Reid Spencer09575ba2007-02-15 03:39:18 +0000307 // If this is a vector type, figure out what type it will decompose into
Chris Lattner49409cb2006-03-16 19:51:18 +0000308 // and how many of the elements it will use.
309 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000310 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner49409cb2006-03-16 19:51:18 +0000311 unsigned NumElts = PTy->getNumElements();
312 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
Bill Wendling47917b62007-04-24 21:13:23 +0000313 MVT::ValueType VecTy = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000314
315 // Divide the input until we get to a supported size. This will always
316 // end with a scalar if the target doesn't support vectors.
Bill Wendling47917b62007-04-24 21:13:23 +0000317 while (NumElts > 1 && !TLI.isTypeLegal(VecTy)) {
Chris Lattner49409cb2006-03-16 19:51:18 +0000318 NumElts >>= 1;
319 NumVectorRegs <<= 1;
Evan Cheng15f269a2007-04-25 18:33:21 +0000320 VecTy = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000321 }
Bill Wendling47917b62007-04-24 21:13:23 +0000322
323 // Check that VecTy isn't a 1-element vector.
324 if (NumElts == 1 && VecTy == MVT::Other)
Chris Lattner7ececaa2006-03-16 23:05:19 +0000325 VT = EltTy;
326 else
Bill Wendling47917b62007-04-24 21:13:23 +0000327 VT = VecTy;
Chris Lattner49409cb2006-03-16 19:51:18 +0000328 }
Bill Wendling47917b62007-04-24 21:13:23 +0000329
Chris Lattner49409cb2006-03-16 19:51:18 +0000330 // The common case is that we will only create one register for this
331 // value. If we have that case, create and return the virtual register.
332 unsigned NV = TLI.getNumElements(VT);
333 if (NV == 1) {
334 // If we are promoting this value, pick the next largest supported type.
335 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
336 unsigned Reg = MakeReg(PromotedType);
337 // If this is a vector of supported or promoted types (e.g. 4 x i16),
338 // create all of the registers.
339 for (unsigned i = 1; i != NumVectorRegs; ++i)
340 MakeReg(PromotedType);
341 return Reg;
342 }
343
344 // If this value is represented with multiple target registers, make sure
345 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng22cf8992006-12-13 20:57:08 +0000346 VT = TLI.getTypeToExpandTo(VT);
347 unsigned R = MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000348 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng22cf8992006-12-13 20:57:08 +0000349 MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000350 return R;
351}
Chris Lattner7a60d912005-01-07 07:47:53 +0000352
353//===----------------------------------------------------------------------===//
354/// SelectionDAGLowering - This is the common target-independent lowering
355/// implementation that is parameterized by a TargetLowering object.
356/// Also, targets can overload any lowering method.
357///
358namespace llvm {
359class SelectionDAGLowering {
360 MachineBasicBlock *CurMBB;
361
Chris Lattner79084302007-02-04 01:31:47 +0000362 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner7a60d912005-01-07 07:47:53 +0000363
Chris Lattner4d9651c2005-01-17 22:19:26 +0000364 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
365 /// them up and then emit token factor nodes when possible. This allows us to
366 /// get simple disambiguation between loads without worrying about alias
367 /// analysis.
368 std::vector<SDOperand> PendingLoads;
369
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000370 /// Case - A struct to record the Value for a switch case, and the
371 /// case's target basic block.
372 struct Case {
373 Constant* Low;
374 Constant* High;
375 MachineBasicBlock* BB;
376
377 Case() : Low(0), High(0), BB(0) { }
378 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
379 Low(low), High(high), BB(bb) { }
380 uint64_t size() const {
381 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
382 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
383 return (rHigh - rLow + 1ULL);
384 }
385 };
386
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000387 struct CaseBits {
388 uint64_t Mask;
389 MachineBasicBlock* BB;
390 unsigned Bits;
391
392 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
393 Mask(mask), BB(bb), Bits(bits) { }
394 };
395
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000396 typedef std::vector<Case> CaseVector;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000397 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000398 typedef CaseVector::iterator CaseItr;
399 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemaned728c12006-03-27 01:32:24 +0000400
401 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
402 /// of conditional branches.
403 struct CaseRec {
404 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
405 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
406
407 /// CaseBB - The MBB in which to emit the compare and branch
408 MachineBasicBlock *CaseBB;
409 /// LT, GE - If nonzero, we know the current case value must be less-than or
410 /// greater-than-or-equal-to these Constants.
411 Constant *LT;
412 Constant *GE;
413 /// Range - A pair of iterators representing the range of case values to be
414 /// processed at this point in the binary search tree.
415 CaseRange Range;
416 };
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000417
418 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000419
420 /// The comparison function for sorting the switch case values in the vector.
421 /// WARNING: Case ranges should be disjoint!
Nate Begemaned728c12006-03-27 01:32:24 +0000422 struct CaseCmp {
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000423 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000424 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
425 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
426 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
427 return CI1->getValue().slt(CI2->getValue());
Nate Begemaned728c12006-03-27 01:32:24 +0000428 }
429 };
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000430
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000431 struct CaseBitsCmp {
432 bool operator () (const CaseBits& C1, const CaseBits& C2) {
433 return C1.Bits > C2.Bits;
434 }
435 };
436
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000437 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemaned728c12006-03-27 01:32:24 +0000438
Chris Lattner7a60d912005-01-07 07:47:53 +0000439public:
440 // TLI - This is information that describes the available target features we
441 // need for lowering. This indicates when operations are unavailable,
442 // implemented with a libcall, etc.
443 TargetLowering &TLI;
444 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000445 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000446
Nate Begemaned728c12006-03-27 01:32:24 +0000447 /// SwitchCases - Vector of CaseBlock structures used to communicate
448 /// SwitchInst code generation information.
449 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +0000450 /// JTCases - Vector of JumpTable structures used to communicate
451 /// SwitchInst code generation information.
452 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000453 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemaned728c12006-03-27 01:32:24 +0000454
Chris Lattner7a60d912005-01-07 07:47:53 +0000455 /// FuncInfo - Information about the function as a whole.
456 ///
457 FunctionLoweringInfo &FuncInfo;
458
459 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000460 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000461 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Anton Korobeynikov70378262007-03-25 15:07:15 +0000462 FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000463 }
464
Chris Lattner4108bb02005-01-17 19:43:36 +0000465 /// getRoot - Return the current virtual root of the Selection DAG.
466 ///
467 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000468 if (PendingLoads.empty())
469 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000470
Chris Lattner4d9651c2005-01-17 22:19:26 +0000471 if (PendingLoads.size() == 1) {
472 SDOperand Root = PendingLoads[0];
473 DAG.setRoot(Root);
474 PendingLoads.clear();
475 return Root;
476 }
477
478 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000479 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
480 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000481 PendingLoads.clear();
482 DAG.setRoot(Root);
483 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000484 }
485
Chris Lattnered0110b2006-10-27 21:36:01 +0000486 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
487
Chris Lattner7a60d912005-01-07 07:47:53 +0000488 void visit(Instruction &I) { visit(I.getOpcode(), I); }
489
490 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000491 // Note: this doesn't use InstVisitor, because it has to work with
492 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000493 switch (Opcode) {
494 default: assert(0 && "Unknown instruction type encountered!");
495 abort();
496 // Build the switch statement using the Instruction.def file.
497#define HANDLE_INST(NUM, OPCODE, CLASS) \
498 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
499#include "llvm/Instruction.def"
500 }
501 }
502
503 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
504
Chris Lattner4024c002006-03-15 22:19:46 +0000505 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000506 const Value *SV, SDOperand Root,
Christopher Lamb8af6d582007-04-22 23:15:30 +0000507 bool isVolatile, unsigned Alignment);
Chris Lattner7a60d912005-01-07 07:47:53 +0000508
509 SDOperand getIntPtrConstant(uint64_t Val) {
510 return DAG.getConstant(Val, TLI.getPointerTy());
511 }
512
Chris Lattner8471b152006-03-16 19:57:50 +0000513 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000514
Chris Lattner79084302007-02-04 01:31:47 +0000515 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000516 SDOperand &N = NodeMap[V];
517 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner79084302007-02-04 01:31:47 +0000518 N = NewN;
Chris Lattner7a60d912005-01-07 07:47:53 +0000519 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000520
Chris Lattner4333f8b2007-04-30 17:29:31 +0000521 RegsForValue GetRegistersForValue(AsmOperandInfo &OpInfo,
Chris Lattner6f87d182006-02-22 22:37:12 +0000522 bool OutReg, bool InReg,
523 std::set<unsigned> &OutputRegs,
524 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000525
Chris Lattnered0110b2006-10-27 21:36:01 +0000526 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
527 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
528 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000529 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000530 void ExportFromCurrentBlock(Value *V);
Jim Laskey31fef782007-02-23 21:45:01 +0000531 void LowerCallTo(Instruction &I,
532 const Type *CalledValueTy, unsigned CallingConv,
533 bool IsTailCall, SDOperand Callee, unsigned OpIdx);
Jim Laskey504e9942007-02-22 15:38:06 +0000534
Chris Lattner7a60d912005-01-07 07:47:53 +0000535 // Terminator instructions.
536 void visitRet(ReturnInst &I);
537 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000538 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000539 void visitUnreachable(UnreachableInst &I) { /* noop */ }
540
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000541 // Helpers for visitSwitch
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000542 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000543 CaseRecVector& WorkList,
544 Value* SV,
545 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000546 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000547 CaseRecVector& WorkList,
548 Value* SV,
549 MachineBasicBlock* Default);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +0000550 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +0000551 CaseRecVector& WorkList,
552 Value* SV,
553 MachineBasicBlock* Default);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000554 bool handleBitTestsSwitchCase(CaseRec& CR,
555 CaseRecVector& WorkList,
556 Value* SV,
557 MachineBasicBlock* Default);
Nate Begemaned728c12006-03-27 01:32:24 +0000558 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +0000559 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
560 void visitBitTestCase(MachineBasicBlock* NextMBB,
561 unsigned Reg,
562 SelectionDAGISel::BitTestCase &B);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000563 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov70378262007-03-25 15:07:15 +0000564 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
565 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemaned728c12006-03-27 01:32:24 +0000566
Chris Lattner7a60d912005-01-07 07:47:53 +0000567 // These all get lowered before this pass.
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000568 void visitInvoke(InvokeInst &I);
Jim Laskey14059d92007-02-25 21:43:59 +0000569 void visitInvoke(InvokeInst &I, bool AsTerminator);
Jim Laskey4b37a4c2007-02-21 22:53:45 +0000570 void visitUnwind(UnwindInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000571
Reid Spencer2eadb532007-01-21 00:29:26 +0000572 void visitScalarBinary(User &I, unsigned OpCode);
573 void visitVectorBinary(User &I, unsigned OpCode);
574 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000575 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000576 void visitAdd(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000577 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000578 visitVectorBinary(I, ISD::VADD);
579 else if (I.getType()->isFloatingPoint())
580 visitScalarBinary(I, ISD::FADD);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000581 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000582 visitScalarBinary(I, ISD::ADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000583 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000584 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000585 void visitMul(User &I) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000586 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +0000587 visitVectorBinary(I, ISD::VMUL);
588 else if (I.getType()->isFloatingPoint())
589 visitScalarBinary(I, ISD::FMUL);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000590 else
Reid Spencer2eadb532007-01-21 00:29:26 +0000591 visitScalarBinary(I, ISD::MUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000592 }
Reid Spencer2eadb532007-01-21 00:29:26 +0000593 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
594 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
595 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
596 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
597 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
598 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
599 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
600 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
601 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
602 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000603 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
604 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000605 void visitICmp(User &I);
606 void visitFCmp(User &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000607 // Visit the conversion instructions
608 void visitTrunc(User &I);
609 void visitZExt(User &I);
610 void visitSExt(User &I);
611 void visitFPTrunc(User &I);
612 void visitFPExt(User &I);
613 void visitFPToUI(User &I);
614 void visitFPToSI(User &I);
615 void visitUIToFP(User &I);
616 void visitSIToFP(User &I);
617 void visitPtrToInt(User &I);
618 void visitIntToPtr(User &I);
619 void visitBitCast(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000620
Chris Lattner67271862006-03-29 00:11:43 +0000621 void visitExtractElement(User &I);
622 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000623 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000624
Chris Lattner7a60d912005-01-07 07:47:53 +0000625 void visitGetElementPtr(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000626 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000627
628 void visitMalloc(MallocInst &I);
629 void visitFree(FreeInst &I);
630 void visitAlloca(AllocaInst &I);
631 void visitLoad(LoadInst &I);
632 void visitStore(StoreInst &I);
633 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
634 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000635 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000636 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000637 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000638
Chris Lattner7a60d912005-01-07 07:47:53 +0000639 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000640 void visitVAArg(VAArgInst &I);
641 void visitVAEnd(CallInst &I);
642 void visitVACopy(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000643
Chris Lattner875def92005-01-11 05:56:49 +0000644 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000645
646 void visitUserOp1(Instruction &I) {
647 assert(0 && "UserOp1 should not exist at instruction selection time!");
648 abort();
649 }
650 void visitUserOp2(Instruction &I) {
651 assert(0 && "UserOp2 should not exist at instruction selection time!");
652 abort();
653 }
654};
655} // end namespace llvm
656
Chris Lattner8471b152006-03-16 19:57:50 +0000657SDOperand SelectionDAGLowering::getValue(const Value *V) {
658 SDOperand &N = NodeMap[V];
659 if (N.Val) return N;
660
661 const Type *VTy = V->getType();
662 MVT::ValueType VT = TLI.getValueType(VTy);
663 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
664 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
665 visit(CE->getOpcode(), *CE);
Chris Lattner79084302007-02-04 01:31:47 +0000666 SDOperand N1 = NodeMap[V];
667 assert(N1.Val && "visit didn't populate the ValueMap!");
668 return N1;
Chris Lattner8471b152006-03-16 19:57:50 +0000669 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
670 return N = DAG.getGlobalAddress(GV, VT);
671 } else if (isa<ConstantPointerNull>(C)) {
672 return N = DAG.getConstant(0, TLI.getPointerTy());
673 } else if (isa<UndefValue>(C)) {
Reid Spencerd84d35b2007-02-15 02:26:10 +0000674 if (!isa<VectorType>(VTy))
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000675 return N = DAG.getNode(ISD::UNDEF, VT);
676
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000677 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000678 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000679 unsigned NumElements = PTy->getNumElements();
680 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
681
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000682 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000683 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
684
685 // Create a VConstant node with generic Vector type.
686 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
687 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000688 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
689 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000690 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
691 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencerd84d35b2007-02-15 02:26:10 +0000692 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner8471b152006-03-16 19:57:50 +0000693 unsigned NumElements = PTy->getNumElements();
694 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000695
696 // Now that we know the number and type of the elements, push a
697 // Constant or ConstantFP node onto the ops list for each element of
698 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000699 SmallVector<SDOperand, 8> Ops;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000700 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000701 for (unsigned i = 0; i != NumElements; ++i)
702 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000703 } else {
704 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
705 SDOperand Op;
706 if (MVT::isFloatingPoint(PVT))
707 Op = DAG.getConstantFP(0, PVT);
708 else
709 Op = DAG.getConstant(0, PVT);
710 Ops.assign(NumElements, Op);
711 }
712
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000713 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000714 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
715 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner79084302007-02-04 01:31:47 +0000716 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
717 Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000718 } else {
719 // Canonicalize all constant ints to be unsigned.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000720 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000721 }
722 }
723
724 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
725 std::map<const AllocaInst*, int>::iterator SI =
726 FuncInfo.StaticAllocaMap.find(AI);
727 if (SI != FuncInfo.StaticAllocaMap.end())
728 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
729 }
730
Chris Lattner8c504cf2007-02-25 18:40:32 +0000731 unsigned InReg = FuncInfo.ValueMap[V];
732 assert(InReg && "Value not in map!");
Chris Lattner8471b152006-03-16 19:57:50 +0000733
734 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000735 if (VT != MVT::Vector) {
Evan Cheng22cf8992006-12-13 20:57:08 +0000736 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000737 // Source must be expanded. This input value is actually coming from the
Chris Lattner8c504cf2007-02-25 18:40:32 +0000738 // register pair InReg and InReg+1.
Evan Cheng22cf8992006-12-13 20:57:08 +0000739 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
740 unsigned NumVals = TLI.getNumElements(VT);
741 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
742 if (NumVals == 1)
743 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
744 else {
745 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
746 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
747 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
748 }
749 } else {
750 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
751 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
752 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
753 N = MVT::isFloatingPoint(VT)
754 ? DAG.getNode(ISD::FP_ROUND, VT, N)
755 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner8471b152006-03-16 19:57:50 +0000756 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000757 } else {
758 // Otherwise, if this is a vector, make it available as a generic vector
759 // here.
760 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000761 const VectorType *PTy = cast<VectorType>(VTy);
762 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000763 PTyLegalElementVT);
764
765 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000766 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000767 if (PTyElementVT == PTyLegalElementVT) {
768 // If the value types are legal, just VBUILD the CopyFromReg nodes.
769 for (unsigned i = 0; i != NE; ++i)
770 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
771 PTyElementVT));
772 } else if (PTyElementVT < PTyLegalElementVT) {
773 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
774 for (unsigned i = 0; i != NE; ++i) {
775 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
776 PTyElementVT);
777 if (MVT::isFloatingPoint(PTyElementVT))
778 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
779 else
780 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
781 Ops.push_back(Op);
782 }
783 } else {
784 // If the register was expanded, use BUILD_PAIR.
785 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
786 for (unsigned i = 0; i != NE/2; ++i) {
787 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
788 PTyElementVT);
789 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
790 PTyElementVT);
791 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
792 }
793 }
794
795 Ops.push_back(DAG.getConstant(NE, MVT::i32));
796 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000797 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000798
799 // Finally, use a VBIT_CONVERT to make this available as the appropriate
800 // vector type.
801 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
802 DAG.getConstant(PTy->getNumElements(),
803 MVT::i32),
804 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000805 }
806
807 return N;
808}
809
810
Chris Lattner7a60d912005-01-07 07:47:53 +0000811void SelectionDAGLowering::visitRet(ReturnInst &I) {
812 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000813 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000814 return;
815 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000816 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000817 NewValues.push_back(getRoot());
818 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
819 SDOperand RetOp = getValue(I.getOperand(i));
820
821 // If this is an integer return value, we need to promote it ourselves to
822 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
823 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000824 // FIXME: C calling convention requires the return type to be promoted to
825 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000826 if (MVT::isInteger(RetOp.getValueType()) &&
827 RetOp.getValueType() < MVT::i64) {
828 MVT::ValueType TmpVT;
829 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
830 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
831 else
832 TmpVT = MVT::i32;
Reid Spencere63b6512006-12-31 05:55:36 +0000833 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +0000834 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Reid Spencere6f81872007-01-03 16:49:33 +0000835 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencera472f662007-04-11 02:44:20 +0000836 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt))
Reid Spencer0917adf2007-01-03 04:25:33 +0000837 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencera472f662007-04-11 02:44:20 +0000838 if (Attrs && Attrs->paramHasAttr(0, ParamAttr::ZExt))
Reid Spencere63b6512006-12-31 05:55:36 +0000839 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer2a34b912007-01-03 05:03:05 +0000840 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000841 }
842 NewValues.push_back(RetOp);
Reid Spencere63b6512006-12-31 05:55:36 +0000843 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000844 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000845 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
846 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000847}
848
Chris Lattnered0110b2006-10-27 21:36:01 +0000849/// ExportFromCurrentBlock - If this condition isn't known to be exported from
850/// the current basic block, add it to ValueMap now so that we'll get a
851/// CopyTo/FromReg.
852void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
853 // No need to export constants.
854 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
855
856 // Already exported?
857 if (FuncInfo.isExportedInst(V)) return;
858
859 unsigned Reg = FuncInfo.InitializeRegForValue(V);
860 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
861}
862
Chris Lattner84a03502006-10-27 23:50:33 +0000863bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
864 const BasicBlock *FromBB) {
865 // The operands of the setcc have to be in this block. We don't know
866 // how to export them from some other block.
867 if (Instruction *VI = dyn_cast<Instruction>(V)) {
868 // Can export from current BB.
869 if (VI->getParent() == FromBB)
870 return true;
871
872 // Is already exported, noop.
873 return FuncInfo.isExportedInst(V);
874 }
875
876 // If this is an argument, we can export it if the BB is the entry block or
877 // if it is already exported.
878 if (isa<Argument>(V)) {
879 if (FromBB == &FromBB->getParent()->getEntryBlock())
880 return true;
881
882 // Otherwise, can only export this if it is already exported.
883 return FuncInfo.isExportedInst(V);
884 }
885
886 // Otherwise, constants can always be exported.
887 return true;
888}
889
Chris Lattnere60ae822006-10-29 21:01:20 +0000890static bool InBlock(const Value *V, const BasicBlock *BB) {
891 if (const Instruction *I = dyn_cast<Instruction>(V))
892 return I->getParent() == BB;
893 return true;
894}
895
Chris Lattnered0110b2006-10-27 21:36:01 +0000896/// FindMergedConditions - If Cond is an expression like
897void SelectionDAGLowering::FindMergedConditions(Value *Cond,
898 MachineBasicBlock *TBB,
899 MachineBasicBlock *FBB,
900 MachineBasicBlock *CurBB,
901 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000902 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencer266e42b2006-12-23 06:05:41 +0000903 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattnered0110b2006-10-27 21:36:01 +0000904
Reid Spencer266e42b2006-12-23 06:05:41 +0000905 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
906 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +0000907 BOp->getParent() != CurBB->getBasicBlock() ||
908 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
909 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000910 const BasicBlock *BB = CurBB->getBasicBlock();
911
Reid Spencer266e42b2006-12-23 06:05:41 +0000912 // If the leaf of the tree is a comparison, merge the condition into
913 // the caseblock.
914 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
915 // The operands of the cmp have to be in this block. We don't know
Chris Lattnerf31b9ef2006-10-29 18:23:37 +0000916 // how to export them from some other block. If this is the first block
917 // of the sequence, no exporting is needed.
918 (CurBB == CurMBB ||
919 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
920 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000921 BOp = cast<Instruction>(Cond);
922 ISD::CondCode Condition;
923 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
924 switch (IC->getPredicate()) {
925 default: assert(0 && "Unknown icmp predicate opcode!");
926 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
927 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
928 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
929 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
930 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
931 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
932 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
933 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
934 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
935 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
936 }
937 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
938 ISD::CondCode FPC, FOC;
939 switch (FC->getPredicate()) {
940 default: assert(0 && "Unknown fcmp predicate opcode!");
941 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
942 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
943 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
944 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
945 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
946 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
947 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
948 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
949 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
950 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
951 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
952 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
953 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
954 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
955 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
956 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
957 }
958 if (FiniteOnlyFPMath())
959 Condition = FOC;
960 else
961 Condition = FPC;
962 } else {
Chris Lattner79084302007-02-04 01:31:47 +0000963 Condition = ISD::SETEQ; // silence warning.
Reid Spencer266e42b2006-12-23 06:05:41 +0000964 assert(0 && "Unknown compare instruction");
Chris Lattnered0110b2006-10-27 21:36:01 +0000965 }
966
Chris Lattnered0110b2006-10-27 21:36:01 +0000967 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000968 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000969 SwitchCases.push_back(CB);
970 return;
971 }
972
973 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000974 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +0000975 NULL, TBB, FBB, CurBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000976 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000977 return;
978 }
979
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000980
981 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000982 MachineFunction::iterator BBI = CurBB;
983 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
984 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
985
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000986 if (Opc == Instruction::Or) {
987 // Codegen X | Y as:
988 // jmp_if_X TBB
989 // jmp TmpBB
990 // TmpBB:
991 // jmp_if_Y TBB
992 // jmp FBB
993 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000994
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000995 // Emit the LHS condition.
996 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
997
998 // Emit the RHS condition into TmpBB.
999 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1000 } else {
1001 assert(Opc == Instruction::And && "Unknown merge op!");
1002 // Codegen X & Y as:
1003 // jmp_if_X TmpBB
1004 // jmp FBB
1005 // TmpBB:
1006 // jmp_if_Y TBB
1007 // jmp FBB
1008 //
1009 // This requires creation of TmpBB after CurBB.
1010
1011 // Emit the LHS condition.
1012 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1013
1014 // Emit the RHS condition into TmpBB.
1015 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1016 }
Chris Lattnered0110b2006-10-27 21:36:01 +00001017}
1018
Chris Lattner427301f2006-10-31 22:37:42 +00001019/// If the set of cases should be emitted as a series of branches, return true.
1020/// If we should emit this as a bunch of and/or'd together conditions, return
1021/// false.
1022static bool
1023ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1024 if (Cases.size() != 2) return true;
1025
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001026 // If this is two comparisons of the same values or'd or and'd together, they
1027 // will get folded into a single comparison, so don't emit two blocks.
1028 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1029 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1030 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1031 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1032 return false;
1033 }
1034
Chris Lattner427301f2006-10-31 22:37:42 +00001035 return true;
1036}
1037
Chris Lattner7a60d912005-01-07 07:47:53 +00001038void SelectionDAGLowering::visitBr(BranchInst &I) {
1039 // Update machine-CFG edges.
1040 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +00001041
1042 // Figure out which block is immediately after the current one.
1043 MachineBasicBlock *NextBlock = 0;
1044 MachineFunction::iterator BBI = CurMBB;
1045 if (++BBI != CurMBB->getParent()->end())
1046 NextBlock = BBI;
1047
1048 if (I.isUnconditional()) {
1049 // If this is not a fall-through branch, emit the branch.
1050 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +00001051 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +00001052 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +00001053
Chris Lattner963ddad2006-10-24 17:57:59 +00001054 // Update machine-CFG edges.
1055 CurMBB->addSuccessor(Succ0MBB);
1056
1057 return;
1058 }
1059
1060 // If this condition is one of the special cases we handle, do special stuff
1061 // now.
1062 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +00001063 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +00001064
1065 // If this is a series of conditions that are or'd or and'd together, emit
1066 // this as a sequence of branches instead of setcc's with and/or operations.
1067 // For example, instead of something like:
1068 // cmp A, B
1069 // C = seteq
1070 // cmp D, E
1071 // F = setle
1072 // or C, F
1073 // jnz foo
1074 // Emit:
1075 // cmp A, B
1076 // je foo
1077 // cmp D, E
1078 // jle foo
1079 //
1080 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1081 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001082 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001083 BOp->getOpcode() == Instruction::Or)) {
1084 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001085 // If the compares in later blocks need to use values not currently
1086 // exported from this block, export them now. This block should always
1087 // be the first entry.
1088 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1089
Chris Lattner427301f2006-10-31 22:37:42 +00001090 // Allow some cases to be rejected.
1091 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001092 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1093 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1094 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1095 }
1096
1097 // Emit the branch for this block.
1098 visitSwitchCase(SwitchCases[0]);
1099 SwitchCases.erase(SwitchCases.begin());
1100 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001101 }
1102
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001103 // Okay, we decided not to do this, remove any inserted MBB's and clear
1104 // SwitchCases.
1105 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1106 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1107
Chris Lattner427301f2006-10-31 22:37:42 +00001108 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001109 }
1110 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001111
1112 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001113 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001114 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner61bcf912006-10-24 18:07:37 +00001115 // Use visitSwitchCase to actually insert the fast branch sequence for this
1116 // cond branch.
1117 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001118}
1119
Nate Begemaned728c12006-03-27 01:32:24 +00001120/// visitSwitchCase - Emits the necessary code to represent a single node in
1121/// the binary search tree resulting from lowering a switch instruction.
1122void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001123 SDOperand Cond;
1124 SDOperand CondLHS = getValue(CB.CmpLHS);
1125
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001126 // Build the setcc now.
1127 if (CB.CmpMHS == NULL) {
1128 // Fold "(X == true)" to X and "(X == false)" to !X to
1129 // handle common cases produced by branch lowering.
1130 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1131 Cond = CondLHS;
1132 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1133 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1134 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1135 } else
1136 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1137 } else {
1138 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov70378262007-03-25 15:07:15 +00001139
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001140 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1141 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1142
1143 SDOperand CmpOp = getValue(CB.CmpMHS);
1144 MVT::ValueType VT = CmpOp.getValueType();
1145
1146 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1147 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1148 } else {
1149 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1150 Cond = DAG.getSetCC(MVT::i1, SUB,
1151 DAG.getConstant(High-Low, VT), ISD::SETULE);
1152 }
1153
1154 }
1155
Nate Begemaned728c12006-03-27 01:32:24 +00001156 // Set NextBlock to be the MBB immediately after the current one, if any.
1157 // This is used to avoid emitting unnecessary branches to the next block.
1158 MachineBasicBlock *NextBlock = 0;
1159 MachineFunction::iterator BBI = CurMBB;
1160 if (++BBI != CurMBB->getParent()->end())
1161 NextBlock = BBI;
1162
1163 // If the lhs block is the next block, invert the condition so that we can
1164 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001165 if (CB.TrueBB == NextBlock) {
1166 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001167 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1168 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1169 }
1170 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001171 DAG.getBasicBlock(CB.TrueBB));
1172 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001173 DAG.setRoot(BrCond);
1174 else
1175 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001176 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001177 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001178 CurMBB->addSuccessor(CB.TrueBB);
1179 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001180}
1181
Anton Korobeynikov70378262007-03-25 15:07:15 +00001182/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001183void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001184 // Emit the code for the jump table
Scott Michel4cfa6162007-04-24 01:24:20 +00001185 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001186 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001187 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1188 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1189 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1190 Table, Index));
1191 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001192}
1193
Anton Korobeynikov70378262007-03-25 15:07:15 +00001194/// visitJumpTableHeader - This function emits necessary code to produce index
1195/// in the JumpTable from switch case.
1196void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1197 SelectionDAGISel::JumpTableHeader &JTH) {
1198 // Subtract the lowest switch case value from the value being switched on
1199 // and conditional branch to default mbb if the result is greater than the
1200 // difference between smallest and largest cases.
1201 SDOperand SwitchOp = getValue(JTH.SValue);
1202 MVT::ValueType VT = SwitchOp.getValueType();
1203 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1204 DAG.getConstant(JTH.First, VT));
1205
1206 // The SDNode we just created, which holds the value being switched on
1207 // minus the the smallest case value, needs to be copied to a virtual
1208 // register so it can be used as an index into the jump table in a
1209 // subsequent basic block. This value may be smaller or larger than the
1210 // target's pointer type, and therefore require extension or truncating.
1211 if (VT > TLI.getPointerTy())
1212 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1213 else
1214 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1215
1216 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1217 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1218 JT.Reg = JumpTableReg;
1219
1220 // Emit the range check for the jump table, and branch to the default
1221 // block for the switch statement if the value being switched on exceeds
1222 // the largest case in the switch.
1223 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1224 DAG.getConstant(JTH.Last-JTH.First,VT),
1225 ISD::SETUGT);
1226
1227 // Set NextBlock to be the MBB immediately after the current one, if any.
1228 // This is used to avoid emitting unnecessary branches to the next block.
1229 MachineBasicBlock *NextBlock = 0;
1230 MachineFunction::iterator BBI = CurMBB;
1231 if (++BBI != CurMBB->getParent()->end())
1232 NextBlock = BBI;
1233
1234 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1235 DAG.getBasicBlock(JT.Default));
1236
1237 if (JT.MBB == NextBlock)
1238 DAG.setRoot(BrCond);
1239 else
1240 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001241 DAG.getBasicBlock(JT.MBB)));
1242
1243 return;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001244}
1245
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001246/// visitBitTestHeader - This function emits necessary code to produce value
1247/// suitable for "bit tests"
1248void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1249 // Subtract the minimum value
1250 SDOperand SwitchOp = getValue(B.SValue);
1251 MVT::ValueType VT = SwitchOp.getValueType();
1252 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1253 DAG.getConstant(B.First, VT));
1254
1255 // Check range
1256 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1257 DAG.getConstant(B.Range, VT),
1258 ISD::SETUGT);
1259
1260 SDOperand ShiftOp;
1261 if (VT > TLI.getShiftAmountTy())
1262 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1263 else
1264 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1265
1266 // Make desired shift
1267 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1268 DAG.getConstant(1, TLI.getPointerTy()),
1269 ShiftOp);
1270
1271 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1272 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), SwitchReg, SwitchVal);
1273 B.Reg = SwitchReg;
1274
1275 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1276 DAG.getBasicBlock(B.Default));
1277
1278 // Set NextBlock to be the MBB immediately after the current one, if any.
1279 // This is used to avoid emitting unnecessary branches to the next block.
1280 MachineBasicBlock *NextBlock = 0;
1281 MachineFunction::iterator BBI = CurMBB;
1282 if (++BBI != CurMBB->getParent()->end())
1283 NextBlock = BBI;
1284
1285 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1286 if (MBB == NextBlock)
1287 DAG.setRoot(BrRange);
1288 else
1289 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1290 DAG.getBasicBlock(MBB)));
1291
1292 CurMBB->addSuccessor(B.Default);
1293 CurMBB->addSuccessor(MBB);
1294
1295 return;
1296}
1297
1298/// visitBitTestCase - this function produces one "bit test"
1299void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1300 unsigned Reg,
1301 SelectionDAGISel::BitTestCase &B) {
1302 // Emit bit tests and jumps
1303 SDOperand SwitchVal = DAG.getCopyFromReg(getRoot(), Reg, TLI.getPointerTy());
1304
1305 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1306 SwitchVal,
1307 DAG.getConstant(B.Mask,
1308 TLI.getPointerTy()));
1309 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultTy(), AndOp,
1310 DAG.getConstant(0, TLI.getPointerTy()),
1311 ISD::SETNE);
1312 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
1313 AndCmp, DAG.getBasicBlock(B.TargetBB));
1314
1315 // Set NextBlock to be the MBB immediately after the current one, if any.
1316 // This is used to avoid emitting unnecessary branches to the next block.
1317 MachineBasicBlock *NextBlock = 0;
1318 MachineFunction::iterator BBI = CurMBB;
1319 if (++BBI != CurMBB->getParent()->end())
1320 NextBlock = BBI;
1321
1322 if (NextMBB == NextBlock)
1323 DAG.setRoot(BrAnd);
1324 else
1325 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1326 DAG.getBasicBlock(NextMBB)));
1327
1328 CurMBB->addSuccessor(B.TargetBB);
1329 CurMBB->addSuccessor(NextMBB);
1330
1331 return;
1332}
Anton Korobeynikov70378262007-03-25 15:07:15 +00001333
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001334void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
Jim Laskey14059d92007-02-25 21:43:59 +00001335 assert(0 && "Should never be visited directly");
1336}
1337void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001338 // Retrieve successors.
1339 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1340 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1341
Jim Laskey14059d92007-02-25 21:43:59 +00001342 if (!AsTerminator) {
1343 // Mark landing pad so that it doesn't get deleted in branch folding.
1344 LandingPad->setIsLandingPad();
1345
1346 // Insert a label before the invoke call to mark the try range.
1347 // This can be used to detect deletion of the invoke via the
1348 // MachineModuleInfo.
1349 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1350 unsigned BeginLabel = MMI->NextLabelID();
1351 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1352 DAG.getConstant(BeginLabel, MVT::i32)));
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001353
Jim Laskey14059d92007-02-25 21:43:59 +00001354 LowerCallTo(I, I.getCalledValue()->getType(),
1355 I.getCallingConv(),
1356 false,
1357 getValue(I.getOperand(0)),
1358 3);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001359
Jim Laskey14059d92007-02-25 21:43:59 +00001360 // Insert a label before the invoke call to mark the try range.
1361 // This can be used to detect deletion of the invoke via the
1362 // MachineModuleInfo.
1363 unsigned EndLabel = MMI->NextLabelID();
1364 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1365 DAG.getConstant(EndLabel, MVT::i32)));
1366
1367 // Inform MachineModuleInfo of range.
1368 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1369
1370 // Update successor info
1371 CurMBB->addSuccessor(Return);
1372 CurMBB->addSuccessor(LandingPad);
1373 } else {
1374 // Drop into normal successor.
1375 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1376 DAG.getBasicBlock(Return)));
1377 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00001378}
1379
1380void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1381}
1382
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001383/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001384/// small case ranges).
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001385bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001386 CaseRecVector& WorkList,
1387 Value* SV,
1388 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001389 Case& BackCase = *(CR.Range.second-1);
1390
1391 // Size is the number of Cases represented by this range.
1392 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001393 if (Size > 3)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001394 return false;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001395
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001396 // Get the MachineFunction which holds the current MBB. This is used when
1397 // inserting any additional MBBs necessary to represent the switch.
1398 MachineFunction *CurMF = CurMBB->getParent();
1399
1400 // Figure out which block is immediately after the current one.
1401 MachineBasicBlock *NextBlock = 0;
1402 MachineFunction::iterator BBI = CR.CaseBB;
1403
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001404 if (++BBI != CurMBB->getParent()->end())
1405 NextBlock = BBI;
1406
1407 // TODO: If any two of the cases has the same destination, and if one value
1408 // is the same as the other, but has one bit unset that the other has set,
1409 // use bit manipulation to do two compares at once. For example:
1410 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1411
1412 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001413 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001414 // The last case block won't fall through into 'NextBlock' if we emit the
1415 // branches in this order. See if rearranging a case value would help.
1416 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001417 if (I->BB == NextBlock) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001418 std::swap(*I, BackCase);
1419 break;
1420 }
1421 }
1422 }
1423
1424 // Create a CaseBlock record representing a conditional branch to
1425 // the Case's target mbb if the value being switched on SV is equal
1426 // to C.
1427 MachineBasicBlock *CurBlock = CR.CaseBB;
1428 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1429 MachineBasicBlock *FallThrough;
1430 if (I != E-1) {
1431 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1432 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1433 } else {
1434 // If the last case doesn't match, go to the default block.
1435 FallThrough = Default;
1436 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001437
1438 Value *RHS, *LHS, *MHS;
1439 ISD::CondCode CC;
1440 if (I->High == I->Low) {
1441 // This is just small small case range :) containing exactly 1 case
1442 CC = ISD::SETEQ;
1443 LHS = SV; RHS = I->High; MHS = NULL;
1444 } else {
1445 CC = ISD::SETLE;
1446 LHS = I->Low; MHS = SV; RHS = I->High;
1447 }
1448 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1449 I->BB, FallThrough, CurBlock);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001450
1451 // If emitting the first comparison, just call visitSwitchCase to emit the
1452 // code into the current block. Otherwise, push the CaseBlock onto the
1453 // vector to be later processed by SDISel, and insert the node's MBB
1454 // before the next MBB.
1455 if (CurBlock == CurMBB)
1456 visitSwitchCase(CB);
1457 else
1458 SwitchCases.push_back(CB);
1459
1460 CurBlock = FallThrough;
1461 }
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001462
1463 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001464}
1465
1466/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001467bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001468 CaseRecVector& WorkList,
1469 Value* SV,
1470 MachineBasicBlock* Default) {
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001471 Case& FrontCase = *CR.Range.first;
1472 Case& BackCase = *(CR.Range.second-1);
1473
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001474 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1475 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1476
1477 uint64_t TSize = 0;
1478 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1479 I!=E; ++I)
1480 TSize += I->size();
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001481
1482 if ((!TLI.isOperationLegal(ISD::BR_JT, MVT::Other) &&
1483 !TLI.isOperationLegal(ISD::BRIND, MVT::Other)) ||
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001484 TSize <= 3)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001485 return false;
1486
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001487 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1488 if (Density < 0.4)
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001489 return false;
1490
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001491 DOUT << "Lowering jump table\n"
1492 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001493 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001494
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001495 // Get the MachineFunction which holds the current MBB. This is used when
1496 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001497 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001498
1499 // Figure out which block is immediately after the current one.
1500 MachineBasicBlock *NextBlock = 0;
1501 MachineFunction::iterator BBI = CR.CaseBB;
1502
1503 if (++BBI != CurMBB->getParent()->end())
1504 NextBlock = BBI;
1505
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001506 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1507
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001508 // Create a new basic block to hold the code for loading the address
1509 // of the jump table, and jumping to it. Update successor information;
1510 // we will either branch to the default case for the switch, or the jump
1511 // table.
1512 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1513 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1514 CR.CaseBB->addSuccessor(Default);
1515 CR.CaseBB->addSuccessor(JumpTableBB);
1516
1517 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001518 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001519 // a case statement, push the case's BB onto the vector, otherwise, push
1520 // the default BB.
1521 std::vector<MachineBasicBlock*> DestBBs;
1522 int64_t TEI = First;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001523 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1524 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1525 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1526
1527 if ((Low <= TEI) && (TEI <= High)) {
1528 DestBBs.push_back(I->BB);
1529 if (TEI==High)
1530 ++I;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001531 } else {
1532 DestBBs.push_back(Default);
1533 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001534 }
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001535
1536 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001537 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001538 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1539 E = DestBBs.end(); I != E; ++I) {
1540 if (!SuccsHandled[(*I)->getNumber()]) {
1541 SuccsHandled[(*I)->getNumber()] = true;
1542 JumpTableBB->addSuccessor(*I);
1543 }
1544 }
1545
1546 // Create a jump table index for this jump table, or return an existing
1547 // one.
1548 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1549
1550 // Set the jump table information so that we can codegen it as a second
1551 // MachineBasicBlock
Scott Michel4cfa6162007-04-24 01:24:20 +00001552 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001553 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1554 (CR.CaseBB == CurMBB));
1555 if (CR.CaseBB == CurMBB)
1556 visitJumpTableHeader(JT, JTH);
1557
1558 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001559
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001560 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001561}
1562
1563/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1564/// 2 subtrees.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001565bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001566 CaseRecVector& WorkList,
1567 Value* SV,
1568 MachineBasicBlock* Default) {
1569 // Get the MachineFunction which holds the current MBB. This is used when
1570 // inserting any additional MBBs necessary to represent the switch.
1571 MachineFunction *CurMF = CurMBB->getParent();
1572
1573 // Figure out which block is immediately after the current one.
1574 MachineBasicBlock *NextBlock = 0;
1575 MachineFunction::iterator BBI = CR.CaseBB;
1576
1577 if (++BBI != CurMBB->getParent()->end())
1578 NextBlock = BBI;
1579
1580 Case& FrontCase = *CR.Range.first;
1581 Case& BackCase = *(CR.Range.second-1);
1582 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1583
1584 // Size is the number of Cases represented by this range.
1585 unsigned Size = CR.Range.second - CR.Range.first;
1586
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001587 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1588 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001589 double FMetric = 0;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001590 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001591
1592 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1593 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001594 uint64_t TSize = 0;
1595 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1596 I!=E; ++I)
1597 TSize += I->size();
1598
1599 uint64_t LSize = FrontCase.size();
1600 uint64_t RSize = TSize-LSize;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001601 DOUT << "Selecting best pivot: \n"
1602 << "First: " << First << ", Last: " << Last <<"\n"
1603 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001604 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001605 J!=E; ++I, ++J) {
1606 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1607 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001608 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001609 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1610 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikovda964a22007-04-09 21:57:03 +00001611 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001612 // Should always split in some non-trivial place
1613 DOUT <<"=>Step\n"
1614 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1615 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1616 << "Metric: " << Metric << "\n";
1617 if (FMetric < Metric) {
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001618 Pivot = J;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001619 FMetric = Metric;
1620 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001621 }
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001622
1623 LSize += J->size();
1624 RSize -= J->size();
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001625 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001626 // If our case is dense we *really* should handle it earlier!
Anton Korobeynikovda964a22007-04-09 21:57:03 +00001627 assert((FMetric > 0) && "Should handle dense range earlier!");
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001628
1629 CaseRange LHSR(CR.Range.first, Pivot);
1630 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001631 Constant *C = Pivot->Low;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001632 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1633
1634 // We know that we branch to the LHS if the Value being switched on is
1635 // less than the Pivot value, C. We use this to optimize our binary
1636 // tree a bit, by recognizing that if SV is greater than or equal to the
1637 // LHS's Case Value, and that Case Value is exactly one less than the
1638 // Pivot's Value, then we can branch directly to the LHS's Target,
1639 // rather than creating a leaf node for it.
1640 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001641 LHSR.first->High == CR.GE &&
1642 cast<ConstantInt>(C)->getSExtValue() ==
1643 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1644 TrueBB = LHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001645 } else {
1646 TrueBB = new MachineBasicBlock(LLVMBB);
1647 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1648 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1649 }
1650
1651 // Similar to the optimization above, if the Value being switched on is
1652 // known to be less than the Constant CR.LT, and the current Case Value
1653 // is CR.LT - 1, then we can branch directly to the target block for
1654 // the current Case Value, rather than emitting a RHS leaf node for it.
1655 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001656 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1657 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1658 FalseBB = RHSR.first->BB;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001659 } else {
1660 FalseBB = new MachineBasicBlock(LLVMBB);
1661 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1662 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1663 }
1664
1665 // Create a CaseBlock record representing a conditional branch to
1666 // the LHS node if the value being switched on SV is less than C.
1667 // Otherwise, branch to LHS.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001668 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1669 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001670
1671 if (CR.CaseBB == CurMBB)
1672 visitSwitchCase(CB);
1673 else
1674 SwitchCases.push_back(CB);
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001675
1676 return true;
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001677}
1678
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001679/// handleBitTestsSwitchCase - if current case range has few destination and
1680/// range span less, than machine word bitwidth, encode case range into series
1681/// of masks and emit bit tests with these masks.
1682bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1683 CaseRecVector& WorkList,
1684 Value* SV,
Chris Lattner7196f092007-04-14 02:26:56 +00001685 MachineBasicBlock* Default){
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001686 unsigned IntPtrBits = getSizeInBits(TLI.getPointerTy());
1687
1688 Case& FrontCase = *CR.Range.first;
1689 Case& BackCase = *(CR.Range.second-1);
1690
1691 // Get the MachineFunction which holds the current MBB. This is used when
1692 // inserting any additional MBBs necessary to represent the switch.
1693 MachineFunction *CurMF = CurMBB->getParent();
1694
1695 unsigned numCmps = 0;
1696 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1697 I!=E; ++I) {
1698 // Single case counts one, case range - two.
1699 if (I->Low == I->High)
1700 numCmps +=1;
1701 else
1702 numCmps +=2;
1703 }
1704
1705 // Count unique destinations
1706 SmallSet<MachineBasicBlock*, 4> Dests;
1707 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1708 Dests.insert(I->BB);
1709 if (Dests.size() > 3)
1710 // Don't bother the code below, if there are too much unique destinations
1711 return false;
1712 }
1713 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1714 << "Total number of comparisons: " << numCmps << "\n";
1715
1716 // Compute span of values.
1717 Constant* minValue = FrontCase.Low;
1718 Constant* maxValue = BackCase.High;
1719 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1720 cast<ConstantInt>(minValue)->getSExtValue();
1721 DOUT << "Compare range: " << range << "\n"
1722 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1723 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1724
Anton Korobeynikovd7ae7f12007-04-26 20:44:04 +00001725 if (range>=IntPtrBits ||
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001726 (!(Dests.size() == 1 && numCmps >= 3) &&
1727 !(Dests.size() == 2 && numCmps >= 5) &&
1728 !(Dests.size() >= 3 && numCmps >= 6)))
1729 return false;
1730
1731 DOUT << "Emitting bit tests\n";
1732 int64_t lowBound = 0;
1733
1734 // Optimize the case where all the case values fit in a
1735 // word without having to subtract minValue. In this case,
1736 // we can optimize away the subtraction.
1737 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikov8a1a84f2007-04-14 13:25:55 +00001738 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001739 range = cast<ConstantInt>(maxValue)->getSExtValue();
1740 } else {
1741 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1742 }
1743
1744 CaseBitsVector CasesBits;
1745 unsigned i, count = 0;
1746
1747 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1748 MachineBasicBlock* Dest = I->BB;
1749 for (i = 0; i < count; ++i)
1750 if (Dest == CasesBits[i].BB)
1751 break;
1752
1753 if (i == count) {
1754 assert((count < 3) && "Too much destinations to test!");
1755 CasesBits.push_back(CaseBits(0, Dest, 0));
1756 count++;
1757 }
1758
1759 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1760 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1761
1762 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikov8a1a84f2007-04-14 13:25:55 +00001763 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001764 CasesBits[i].Bits++;
1765 }
1766
1767 }
1768 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1769
1770 SelectionDAGISel::BitTestInfo BTC;
1771
1772 // Figure out which block is immediately after the current one.
1773 MachineFunction::iterator BBI = CR.CaseBB;
1774 ++BBI;
1775
1776 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1777
1778 DOUT << "Cases:\n";
1779 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1780 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1781 << ", BB: " << CasesBits[i].BB << "\n";
1782
1783 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
1784 CurMF->getBasicBlockList().insert(BBI, CaseBB);
1785 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
1786 CaseBB,
1787 CasesBits[i].BB));
1788 }
1789
1790 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohen0475f3b2007-04-09 14:32:59 +00001791 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001792 CR.CaseBB, Default, BTC);
1793
1794 if (CR.CaseBB == CurMBB)
1795 visitBitTestHeader(BTB);
1796
1797 BitTestCases.push_back(BTB);
1798
1799 return true;
1800}
1801
1802
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001803// Clusterify - Transform simple list of Cases into list of CaseRange's
1804unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1805 const SwitchInst& SI) {
1806 unsigned numCmps = 0;
1807
1808 // Start with "simple" cases
1809 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1810 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1811 Cases.push_back(Case(SI.getSuccessorValue(i),
1812 SI.getSuccessorValue(i),
1813 SMBB));
1814 }
1815 sort(Cases.begin(), Cases.end(), CaseCmp());
1816
1817 // Merge case into clusters
1818 if (Cases.size()>=2)
1819 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
1820 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1821 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1822 MachineBasicBlock* nextBB = J->BB;
1823 MachineBasicBlock* currentBB = I->BB;
1824
1825 // If the two neighboring cases go to the same destination, merge them
1826 // into a single case.
1827 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1828 I->High = J->High;
1829 J = Cases.erase(J);
1830 } else {
1831 I = J++;
1832 }
1833 }
1834
1835 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1836 if (I->Low != I->High)
1837 // A range counts double, since it requires two compares.
1838 ++numCmps;
1839 }
1840
1841 return numCmps;
1842}
1843
1844void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemaned728c12006-03-27 01:32:24 +00001845 // Figure out which block is immediately after the current one.
1846 MachineBasicBlock *NextBlock = 0;
1847 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001848
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001849 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattner6d6fc262006-10-22 21:36:53 +00001850
Nate Begemaned728c12006-03-27 01:32:24 +00001851 // If there is only the default destination, branch to it if it is not the
1852 // next basic block. Otherwise, just fall through.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001853 if (SI.getNumOperands() == 2) {
Nate Begemaned728c12006-03-27 01:32:24 +00001854 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001855
Nate Begemaned728c12006-03-27 01:32:24 +00001856 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001857 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001858 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001859 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001860
Chris Lattner6d6fc262006-10-22 21:36:53 +00001861 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001862 return;
1863 }
1864
1865 // If there are any non-default case statements, create a vector of Cases
1866 // representing each one, and sort the vector so that we can efficiently
1867 // create a binary search tree from them.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001868 CaseVector Cases;
1869 unsigned numCmps = Clusterify(Cases, SI);
1870 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1871 << ". Total compares: " << numCmps << "\n";
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001872
Nate Begemaned728c12006-03-27 01:32:24 +00001873 // Get the Value to be switched on and default basic blocks, which will be
1874 // inserted into CaseBlock records, representing basic blocks in the binary
1875 // search tree.
Anton Korobeynikov915e6172007-04-04 21:14:49 +00001876 Value *SV = SI.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001877
Nate Begemaned728c12006-03-27 01:32:24 +00001878 // Push the initial CaseRec onto the worklist
Anton Korobeynikov3a9d6812007-03-27 11:29:11 +00001879 CaseRecVector WorkList;
Anton Korobeynikov70378262007-03-25 15:07:15 +00001880 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1881
1882 while (!WorkList.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00001883 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov70378262007-03-25 15:07:15 +00001884 CaseRec CR = WorkList.back();
1885 WorkList.pop_back();
Anton Korobeynikov70378262007-03-25 15:07:15 +00001886
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001887 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1888 continue;
1889
Anton Korobeynikov70378262007-03-25 15:07:15 +00001890 // If the range has few cases (two or less) emit a series of specific
1891 // tests.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001892 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1893 continue;
1894
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00001895 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov70378262007-03-25 15:07:15 +00001896 // target supports indirect branches, then emit a jump table rather than
1897 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikov37a0bfe2007-03-27 12:05:48 +00001898 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1899 continue;
1900
1901 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1902 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1903 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001904 }
1905}
1906
Anton Korobeynikov70378262007-03-25 15:07:15 +00001907
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001908void SelectionDAGLowering::visitSub(User &I) {
1909 // -0.0 - X --> fneg
Reid Spencer2eadb532007-01-21 00:29:26 +00001910 const Type *Ty = I.getType();
Reid Spencerd84d35b2007-02-15 02:26:10 +00001911 if (isa<VectorType>(Ty)) {
Reid Spencer2eadb532007-01-21 00:29:26 +00001912 visitVectorBinary(I, ISD::VSUB);
1913 } else if (Ty->isFloatingPoint()) {
Chris Lattner6f3b5772005-09-28 22:28:18 +00001914 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1915 if (CFP->isExactlyValue(-0.0)) {
1916 SDOperand Op2 = getValue(I.getOperand(1));
1917 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1918 return;
1919 }
Reid Spencer2eadb532007-01-21 00:29:26 +00001920 visitScalarBinary(I, ISD::FSUB);
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001921 } else
Reid Spencer2eadb532007-01-21 00:29:26 +00001922 visitScalarBinary(I, ISD::SUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001923}
1924
Reid Spencer2eadb532007-01-21 00:29:26 +00001925void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001926 SDOperand Op1 = getValue(I.getOperand(0));
1927 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer2eadb532007-01-21 00:29:26 +00001928
1929 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001930}
1931
Reid Spencer2eadb532007-01-21 00:29:26 +00001932void
1933SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001934 assert(isa<VectorType>(I.getType()));
1935 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer2eadb532007-01-21 00:29:26 +00001936 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001937
Reid Spencer2eadb532007-01-21 00:29:26 +00001938 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1939 getValue(I.getOperand(0)),
1940 getValue(I.getOperand(1)),
1941 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1942 Typ));
1943}
1944
1945void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1946 unsigned VectorOp) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00001947 if (isa<VectorType>(I.getType()))
Reid Spencer2eadb532007-01-21 00:29:26 +00001948 visitVectorBinary(I, VectorOp);
1949 else
1950 visitScalarBinary(I, ScalarOp);
Nate Begeman127321b2005-11-18 07:42:56 +00001951}
Chris Lattner96c26752005-01-19 22:31:21 +00001952
Nate Begeman127321b2005-11-18 07:42:56 +00001953void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1954 SDOperand Op1 = getValue(I.getOperand(0));
1955 SDOperand Op2 = getValue(I.getOperand(1));
1956
Reid Spencer2341c222007-02-02 02:16:23 +00001957 if (TLI.getShiftAmountTy() < Op2.getValueType())
1958 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1959 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1960 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begeman127321b2005-11-18 07:42:56 +00001961
Chris Lattner7a60d912005-01-07 07:47:53 +00001962 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1963}
1964
Reid Spencerd9436b62006-11-20 01:22:35 +00001965void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001966 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1967 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1968 predicate = IC->getPredicate();
1969 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1970 predicate = ICmpInst::Predicate(IC->getPredicate());
1971 SDOperand Op1 = getValue(I.getOperand(0));
1972 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencerd9436b62006-11-20 01:22:35 +00001973 ISD::CondCode Opcode;
Reid Spencer266e42b2006-12-23 06:05:41 +00001974 switch (predicate) {
Reid Spencerd9436b62006-11-20 01:22:35 +00001975 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1976 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1977 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1978 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1979 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1980 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1981 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1982 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1983 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1984 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1985 default:
1986 assert(!"Invalid ICmp predicate value");
1987 Opcode = ISD::SETEQ;
1988 break;
1989 }
1990 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1991}
1992
1993void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001994 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1995 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1996 predicate = FC->getPredicate();
1997 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1998 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner7a60d912005-01-07 07:47:53 +00001999 SDOperand Op1 = getValue(I.getOperand(0));
2000 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00002001 ISD::CondCode Condition, FOC, FPC;
2002 switch (predicate) {
2003 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2004 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2005 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2006 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2007 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2008 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2009 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2010 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2011 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2012 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2013 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2014 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2015 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2016 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2017 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2018 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2019 default:
2020 assert(!"Invalid FCmp predicate value");
2021 FOC = FPC = ISD::SETFALSE;
2022 break;
2023 }
2024 if (FiniteOnlyFPMath())
2025 Condition = FOC;
2026 else
2027 Condition = FPC;
2028 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner7a60d912005-01-07 07:47:53 +00002029}
2030
2031void SelectionDAGLowering::visitSelect(User &I) {
2032 SDOperand Cond = getValue(I.getOperand(0));
2033 SDOperand TrueVal = getValue(I.getOperand(1));
2034 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencerd84d35b2007-02-15 02:26:10 +00002035 if (!isa<VectorType>(I.getType())) {
Chris Lattner02274a52006-04-08 22:22:57 +00002036 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2037 TrueVal, FalseVal));
2038 } else {
2039 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
2040 *(TrueVal.Val->op_end()-2),
2041 *(TrueVal.Val->op_end()-1)));
2042 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002043}
2044
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002045
2046void SelectionDAGLowering::visitTrunc(User &I) {
2047 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2048 SDOperand N = getValue(I.getOperand(0));
2049 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2050 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2051}
2052
2053void SelectionDAGLowering::visitZExt(User &I) {
2054 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2055 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2056 SDOperand N = getValue(I.getOperand(0));
2057 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2058 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2059}
2060
2061void SelectionDAGLowering::visitSExt(User &I) {
2062 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2063 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2064 SDOperand N = getValue(I.getOperand(0));
2065 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2066 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2067}
2068
2069void SelectionDAGLowering::visitFPTrunc(User &I) {
2070 // FPTrunc is never a no-op cast, no need to check
2071 SDOperand N = getValue(I.getOperand(0));
2072 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2073 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
2074}
2075
2076void SelectionDAGLowering::visitFPExt(User &I){
2077 // FPTrunc is never a no-op cast, no need to check
2078 SDOperand N = getValue(I.getOperand(0));
2079 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2080 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2081}
2082
2083void SelectionDAGLowering::visitFPToUI(User &I) {
2084 // FPToUI is never a no-op cast, no need to check
2085 SDOperand N = getValue(I.getOperand(0));
2086 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2087 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2088}
2089
2090void SelectionDAGLowering::visitFPToSI(User &I) {
2091 // FPToSI is never a no-op cast, no need to check
2092 SDOperand N = getValue(I.getOperand(0));
2093 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2094 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2095}
2096
2097void SelectionDAGLowering::visitUIToFP(User &I) {
2098 // UIToFP is never a no-op cast, no need to check
2099 SDOperand N = getValue(I.getOperand(0));
2100 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2101 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2102}
2103
2104void SelectionDAGLowering::visitSIToFP(User &I){
2105 // UIToFP is never a no-op cast, no need to check
2106 SDOperand N = getValue(I.getOperand(0));
2107 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2108 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2109}
2110
2111void SelectionDAGLowering::visitPtrToInt(User &I) {
2112 // What to do depends on the size of the integer and the size of the pointer.
2113 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner7a60d912005-01-07 07:47:53 +00002114 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00002115 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00002116 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002117 SDOperand Result;
2118 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2119 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2120 else
2121 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2122 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2123 setValue(&I, Result);
2124}
Chris Lattner7a60d912005-01-07 07:47:53 +00002125
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002126void SelectionDAGLowering::visitIntToPtr(User &I) {
2127 // What to do depends on the size of the integer and the size of the pointer.
2128 // We can either truncate, zero extend, or no-op, accordingly.
2129 SDOperand N = getValue(I.getOperand(0));
2130 MVT::ValueType SrcVT = N.getValueType();
2131 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2132 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2133 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2134 else
2135 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2136 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2137}
2138
2139void SelectionDAGLowering::visitBitCast(User &I) {
2140 SDOperand N = getValue(I.getOperand(0));
2141 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00002142 if (DestVT == MVT::Vector) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002143 // This is a cast to a vector from something else.
2144 // Get information about the output vector.
Reid Spencerd84d35b2007-02-15 02:26:10 +00002145 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00002146 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2147 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
2148 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
2149 DAG.getValueType(EltVT)));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002150 return;
2151 }
2152 MVT::ValueType SrcVT = N.getValueType();
2153 if (SrcVT == MVT::Vector) {
2154 // This is a cast from a vctor to something else.
2155 // Get information about the input vector.
Chris Lattner2f4119a2006-03-22 20:09:35 +00002156 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002157 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00002158 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00002159
2160 // BitCast assures us that source and destination are the same size so this
2161 // is either a BIT_CONVERT or a no-op.
2162 if (DestVT != N.getValueType())
2163 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2164 else
2165 setValue(&I, N); // noop cast.
Chris Lattner7a60d912005-01-07 07:47:53 +00002166}
2167
Chris Lattner67271862006-03-29 00:11:43 +00002168void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00002169 SDOperand InVec = getValue(I.getOperand(0));
2170 SDOperand InVal = getValue(I.getOperand(1));
2171 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2172 getValue(I.getOperand(2)));
2173
Chris Lattner29b23012006-03-19 01:17:20 +00002174 SDOperand Num = *(InVec.Val->op_end()-2);
2175 SDOperand Typ = *(InVec.Val->op_end()-1);
2176 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
2177 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00002178}
2179
Chris Lattner67271862006-03-29 00:11:43 +00002180void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00002181 SDOperand InVec = getValue(I.getOperand(0));
2182 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2183 getValue(I.getOperand(1)));
2184 SDOperand Typ = *(InVec.Val->op_end()-1);
2185 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
2186 TLI.getValueType(I.getType()), InVec, InIdx));
2187}
Chris Lattner32206f52006-03-18 01:44:44 +00002188
Chris Lattner098c01e2006-04-08 04:15:24 +00002189void SelectionDAGLowering::visitShuffleVector(User &I) {
2190 SDOperand V1 = getValue(I.getOperand(0));
2191 SDOperand V2 = getValue(I.getOperand(1));
2192 SDOperand Mask = getValue(I.getOperand(2));
2193
2194 SDOperand Num = *(V1.Val->op_end()-2);
2195 SDOperand Typ = *(V2.Val->op_end()-1);
2196 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
2197 V1, V2, Mask, Num, Typ));
2198}
2199
2200
Chris Lattner7a60d912005-01-07 07:47:53 +00002201void SelectionDAGLowering::visitGetElementPtr(User &I) {
2202 SDOperand N = getValue(I.getOperand(0));
2203 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00002204
2205 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2206 OI != E; ++OI) {
2207 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00002208 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002209 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00002210 if (Field) {
2211 // N = N + Offset
Chris Lattnerc473d8e2007-02-10 19:55:17 +00002212 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner7a60d912005-01-07 07:47:53 +00002213 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00002214 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00002215 }
2216 Ty = StTy->getElementType(Field);
2217 } else {
2218 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00002219
Chris Lattner43535a12005-11-09 04:45:33 +00002220 // If this is a constant subscript, handle it quickly.
2221 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002222 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00002223 uint64_t Offs =
Evan Cheng8ec52832007-01-05 01:46:20 +00002224 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00002225 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
2226 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00002227 }
Chris Lattner43535a12005-11-09 04:45:33 +00002228
2229 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00002230 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00002231 SDOperand IdxN = getValue(Idx);
2232
2233 // If the index is smaller or larger than intptr_t, truncate or extend
2234 // it.
2235 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencere63b6512006-12-31 05:55:36 +00002236 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner43535a12005-11-09 04:45:33 +00002237 } else if (IdxN.getValueType() > N.getValueType())
2238 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2239
2240 // If this is a multiply by a power of two, turn it into a shl
2241 // immediately. This is a very common case.
2242 if (isPowerOf2_64(ElementSize)) {
2243 unsigned Amt = Log2_64(ElementSize);
2244 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00002245 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00002246 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2247 continue;
2248 }
2249
2250 SDOperand Scale = getIntPtrConstant(ElementSize);
2251 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2252 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00002253 }
2254 }
2255 setValue(&I, N);
2256}
2257
2258void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2259 // If this is a fixed sized alloca in the entry block of the function,
2260 // allocate it statically on the stack.
2261 if (FuncInfo.StaticAllocaMap.count(&I))
2262 return; // getValue will auto-populate this.
2263
2264 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00002265 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner50ee0e42007-01-20 22:35:55 +00002266 unsigned Align =
Chris Lattner945e4372007-02-14 05:52:17 +00002267 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner50ee0e42007-01-20 22:35:55 +00002268 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00002269
2270 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00002271 MVT::ValueType IntPtr = TLI.getPointerTy();
2272 if (IntPtr < AllocSize.getValueType())
2273 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2274 else if (IntPtr > AllocSize.getValueType())
2275 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00002276
Chris Lattnereccb73d2005-01-22 23:04:37 +00002277 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00002278 getIntPtrConstant(TySize));
2279
2280 // Handle alignment. If the requested alignment is less than or equal to the
2281 // stack alignment, ignore it and round the size of the allocation up to the
2282 // stack alignment size. If the size is greater than the stack alignment, we
2283 // note this in the DYNAMIC_STACKALLOC node.
2284 unsigned StackAlign =
2285 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2286 if (Align <= StackAlign) {
2287 Align = 0;
2288 // Add SA-1 to the size.
2289 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2290 getIntPtrConstant(StackAlign-1));
2291 // Mask out the low bits for alignment purposes.
2292 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2293 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2294 }
2295
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002296 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00002297 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2298 MVT::Other);
2299 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner79084302007-02-04 01:31:47 +00002300 setValue(&I, DSA);
2301 DAG.setRoot(DSA.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002302
2303 // Inform the Frame Information that we have just allocated a variable-sized
2304 // object.
2305 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2306}
2307
Chris Lattner7a60d912005-01-07 07:47:53 +00002308void SelectionDAGLowering::visitLoad(LoadInst &I) {
2309 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00002310
Chris Lattner4d9651c2005-01-17 22:19:26 +00002311 SDOperand Root;
2312 if (I.isVolatile())
2313 Root = getRoot();
2314 else {
2315 // Do not serialize non-volatile loads against each other.
2316 Root = DAG.getRoot();
2317 }
Chris Lattner4024c002006-03-15 22:19:46 +00002318
Evan Chenge71fe34d2006-10-09 20:57:25 +00002319 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb8af6d582007-04-22 23:15:30 +00002320 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner4024c002006-03-15 22:19:46 +00002321}
2322
2323SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00002324 const Value *SV, SDOperand Root,
Christopher Lamb8af6d582007-04-22 23:15:30 +00002325 bool isVolatile,
2326 unsigned Alignment) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00002327 SDOperand L;
Reid Spencerd84d35b2007-02-15 02:26:10 +00002328 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00002329 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00002330 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
2331 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00002332 } else {
Christopher Lamb8af6d582007-04-22 23:15:30 +00002333 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2334 isVolatile, Alignment);
Nate Begemanb2e089c2005-11-19 00:36:38 +00002335 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00002336
Chris Lattner4024c002006-03-15 22:19:46 +00002337 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00002338 DAG.setRoot(L.getValue(1));
2339 else
2340 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00002341
2342 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00002343}
2344
2345
2346void SelectionDAGLowering::visitStore(StoreInst &I) {
2347 Value *SrcV = I.getOperand(0);
2348 SDOperand Src = getValue(SrcV);
2349 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng258657e2006-12-20 01:27:29 +00002350 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb8af6d582007-04-22 23:15:30 +00002351 I.isVolatile(), I.getAlignment()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002352}
2353
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002354/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
2355/// access memory and has no other side effects at all.
2356static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
2357#define GET_NO_MEMORY_INTRINSICS
2358#include "llvm/Intrinsics.gen"
2359#undef GET_NO_MEMORY_INTRINSICS
2360 return false;
2361}
2362
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002363// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
2364// have any side-effects or if it only reads memory.
2365static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
2366#define GET_SIDE_EFFECT_INFO
2367#include "llvm/Intrinsics.gen"
2368#undef GET_SIDE_EFFECT_INFO
2369 return false;
2370}
2371
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002372/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2373/// node.
2374void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2375 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00002376 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002377 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002378
2379 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002380 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002381 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2382 if (OnlyLoad) {
2383 // We don't need to serialize loads against other loads.
2384 Ops.push_back(DAG.getRoot());
2385 } else {
2386 Ops.push_back(getRoot());
2387 }
2388 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002389
2390 // Add the intrinsic ID as an integer operand.
2391 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2392
2393 // Add all operands of the call to the operand list.
2394 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2395 SDOperand Op = getValue(I.getOperand(i));
2396
Reid Spencer09575ba2007-02-15 03:39:18 +00002397 // If this is a vector type, force it to the right vector type.
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002398 if (Op.getValueType() == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002399 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002400 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
2401
2402 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
2403 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
2404 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
2405 }
2406
2407 assert(TLI.isTypeLegal(Op.getValueType()) &&
2408 "Intrinsic uses a non-legal type?");
2409 Ops.push_back(Op);
2410 }
2411
2412 std::vector<MVT::ValueType> VTs;
2413 if (I.getType() != Type::VoidTy) {
2414 MVT::ValueType VT = TLI.getValueType(I.getType());
2415 if (VT == MVT::Vector) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002416 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002417 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2418
2419 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2420 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2421 }
2422
2423 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2424 VTs.push_back(VT);
2425 }
2426 if (HasChain)
2427 VTs.push_back(MVT::Other);
2428
Chris Lattnerbd887772006-08-14 23:53:35 +00002429 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2430
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002431 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00002432 SDOperand Result;
2433 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00002434 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2435 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002436 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00002437 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2438 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002439 else
Chris Lattnerbd887772006-08-14 23:53:35 +00002440 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2441 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00002442
Chris Lattnera9c59156b2006-04-02 03:41:14 +00002443 if (HasChain) {
2444 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2445 if (OnlyLoad)
2446 PendingLoads.push_back(Chain);
2447 else
2448 DAG.setRoot(Chain);
2449 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002450 if (I.getType() != Type::VoidTy) {
Reid Spencerd84d35b2007-02-15 02:26:10 +00002451 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002452 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
2453 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
2454 DAG.getConstant(PTy->getNumElements(), MVT::i32),
2455 DAG.getValueType(EVT));
2456 }
2457 setValue(&I, Result);
2458 }
2459}
2460
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002461/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2462/// we want to emit this as a call to a named external function, return the name
2463/// otherwise lower it and return null.
2464const char *
2465SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2466 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00002467 default:
2468 // By default, turn this into a target intrinsic node.
2469 visitTargetIntrinsic(I, Intrinsic);
2470 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002471 case Intrinsic::vastart: visitVAStart(I); return 0;
2472 case Intrinsic::vaend: visitVAEnd(I); return 0;
2473 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemaneda59972007-01-29 22:58:52 +00002474 case Intrinsic::returnaddress:
2475 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2476 getValue(I.getOperand(1))));
2477 return 0;
2478 case Intrinsic::frameaddress:
2479 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2480 getValue(I.getOperand(1))));
2481 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002482 case Intrinsic::setjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002483 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002484 break;
2485 case Intrinsic::longjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00002486 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002487 break;
Chris Lattner093c1592006-03-03 00:00:25 +00002488 case Intrinsic::memcpy_i32:
2489 case Intrinsic::memcpy_i64:
2490 visitMemIntrinsic(I, ISD::MEMCPY);
2491 return 0;
2492 case Intrinsic::memset_i32:
2493 case Intrinsic::memset_i64:
2494 visitMemIntrinsic(I, ISD::MEMSET);
2495 return 0;
2496 case Intrinsic::memmove_i32:
2497 case Intrinsic::memmove_i64:
2498 visitMemIntrinsic(I, ISD::MEMMOVE);
2499 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002500
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002501 case Intrinsic::dbg_stoppoint: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002502 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002503 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002504 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002505 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00002506
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002507 Ops[0] = getRoot();
2508 Ops[1] = getValue(SPI.getLineValue());
2509 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00002510
Jim Laskeyc56315c2007-01-26 21:22:28 +00002511 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00002512 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00002513 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2514
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002515 Ops[3] = DAG.getString(CompileUnit->getFileName());
2516 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00002517
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002518 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00002519 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002520
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002521 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00002522 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00002523 case Intrinsic::dbg_region_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002524 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002525 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002526 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2527 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002528 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002529 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002530 }
2531
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002532 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002533 }
2534 case Intrinsic::dbg_region_end: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002535 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002536 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002537 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2538 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002539 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002540 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002541 }
2542
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002543 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002544 }
2545 case Intrinsic::dbg_func_start: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002546 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002547 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002548 if (MMI && FSI.getSubprogram() &&
2549 MMI->Verify(FSI.getSubprogram())) {
2550 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskeyf9e54452007-01-26 14:34:52 +00002551 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002552 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002553 }
2554
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002555 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002556 }
2557 case Intrinsic::dbg_declare: {
Jim Laskeyc56315c2007-01-26 21:22:28 +00002558 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00002559 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeyc56315c2007-01-26 21:22:28 +00002560 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00002561 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002562 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeyc56315c2007-01-26 21:22:28 +00002563 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00002564 }
2565
2566 return 0;
2567 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002568
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002569 case Intrinsic::eh_exception: {
2570 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2571
Jim Laskey504e9942007-02-22 15:38:06 +00002572 if (MMI) {
2573 // Add a label to mark the beginning of the landing pad. Deletion of the
2574 // landing pad can thus be detected via the MachineModuleInfo.
2575 unsigned LabelID = MMI->addLandingPad(CurMBB);
2576 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2577 DAG.getConstant(LabelID, MVT::i32)));
2578
2579 // Mark exception register as live in.
2580 unsigned Reg = TLI.getExceptionAddressRegister();
2581 if (Reg) CurMBB->addLiveIn(Reg);
2582
2583 // Insert the EXCEPTIONADDR instruction.
2584 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2585 SDOperand Ops[1];
2586 Ops[0] = DAG.getRoot();
2587 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2588 setValue(&I, Op);
2589 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002590 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002591 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey504e9942007-02-22 15:38:06 +00002592 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002593 return 0;
2594 }
2595
Jim Laskeyd5453d72007-03-01 20:24:30 +00002596 case Intrinsic::eh_selector:
2597 case Intrinsic::eh_filter:{
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002598 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2599
Jim Laskey504e9942007-02-22 15:38:06 +00002600 if (MMI) {
2601 // Inform the MachineModuleInfo of the personality for this landing pad.
Jim Laskey44c37e72007-02-22 16:10:05 +00002602 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2603 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2604 isa<Function>(CE->getOperand(0)) &&
2605 "Personality should be a function");
2606 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
Jim Laskeyd5453d72007-03-01 20:24:30 +00002607 if (Intrinsic == Intrinsic::eh_filter)
2608 MMI->setIsFilterLandingPad(CurMBB);
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002609
Jim Laskey504e9942007-02-22 15:38:06 +00002610 // Gather all the type infos for this landing pad and pass them along to
2611 // MachineModuleInfo.
2612 std::vector<GlobalVariable *> TyInfo;
2613 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
Chris Lattner784fe9d2007-04-27 01:20:11 +00002614 Constant *C = cast<Constant>(I.getOperand(i));
2615 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
2616 TyInfo.push_back(GV);
2617 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2618 assert(CE->getOpcode() == Instruction::BitCast &&
2619 isa<GlobalVariable>(CE->getOperand(0))
2620 && "TypeInfo must be a global variable or NULL");
Jim Laskey44c37e72007-02-22 16:10:05 +00002621 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2622 } else {
Chris Lattner784fe9d2007-04-27 01:20:11 +00002623 ConstantInt *CI = dyn_cast<ConstantInt>(C);
2624 assert(CI && CI->isNullValue() &&
2625 "TypeInfo must be a global variable or NULL");
Jim Laskey44c37e72007-02-22 16:10:05 +00002626 TyInfo.push_back(NULL);
Jim Laskey504e9942007-02-22 15:38:06 +00002627 }
Jim Laskey504e9942007-02-22 15:38:06 +00002628 }
2629 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2630
2631 // Mark exception selector register as live in.
2632 unsigned Reg = TLI.getExceptionSelectorRegister();
2633 if (Reg) CurMBB->addLiveIn(Reg);
2634
2635 // Insert the EHSELECTION instruction.
Jim Laskeycf465fc2007-02-28 18:37:04 +00002636 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
Jim Laskey504e9942007-02-22 15:38:06 +00002637 SDOperand Ops[2];
2638 Ops[0] = getValue(I.getOperand(1));
2639 Ops[1] = getRoot();
2640 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2641 setValue(&I, Op);
2642 DAG.setRoot(Op.getValue(1));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002643 } else {
Jim Laskeycf465fc2007-02-28 18:37:04 +00002644 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002645 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002646
2647 return 0;
2648 }
2649
2650 case Intrinsic::eh_typeid_for: {
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002651 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002652
Jim Laskey504e9942007-02-22 15:38:06 +00002653 if (MMI) {
2654 // Find the type id for the given typeinfo.
2655 GlobalVariable *GV = NULL;
Jim Laskey44c37e72007-02-22 16:10:05 +00002656 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1));
2657 if (CE && CE->getOpcode() == Instruction::BitCast &&
2658 isa<GlobalVariable>(CE->getOperand(0))) {
2659 GV = cast<GlobalVariable>(CE->getOperand(0));
2660 } else {
2661 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2662 assert(CI && CI->getZExtValue() == 0 &&
2663 "TypeInfo must be a global variable typeinfo or NULL");
2664 GV = NULL;
Jim Laskey504e9942007-02-22 15:38:06 +00002665 }
2666
2667 unsigned TypeID = MMI->getTypeIDFor(GV);
2668 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskeye1d1c052007-02-24 09:45:44 +00002669 } else {
2670 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey504e9942007-02-22 15:38:06 +00002671 }
Jim Laskey4b37a4c2007-02-21 22:53:45 +00002672
2673 return 0;
2674 }
2675
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002676 case Intrinsic::sqrt_f32:
2677 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002678 setValue(&I, DAG.getNode(ISD::FSQRT,
2679 getValue(I.getOperand(1)).getValueType(),
2680 getValue(I.getOperand(1))));
2681 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00002682 case Intrinsic::powi_f32:
2683 case Intrinsic::powi_f64:
2684 setValue(&I, DAG.getNode(ISD::FPOWI,
2685 getValue(I.getOperand(1)).getValueType(),
2686 getValue(I.getOperand(1)),
2687 getValue(I.getOperand(2))));
2688 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002689 case Intrinsic::pcmarker: {
2690 SDOperand Tmp = getValue(I.getOperand(1));
2691 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2692 return 0;
2693 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002694 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002695 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002696 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2697 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2698 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002699 setValue(&I, Tmp);
2700 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002701 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002702 }
Chris Lattnerf269d842007-04-10 03:20:39 +00002703 case Intrinsic::part_select: {
Reid Spencer85460ac2007-04-05 01:20:18 +00002704 // Currently not implemented: just abort
Reid Spencerc6251a72007-04-12 02:48:46 +00002705 assert(0 && "part_select intrinsic not implemented");
2706 abort();
2707 }
2708 case Intrinsic::part_set: {
2709 // Currently not implemented: just abort
2710 assert(0 && "part_set intrinsic not implemented");
Reid Spencer85460ac2007-04-05 01:20:18 +00002711 abort();
Reid Spencercce90f52007-04-04 23:48:25 +00002712 }
Reid Spencer3a0843e2007-04-01 07:34:11 +00002713 case Intrinsic::bswap:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002714 setValue(&I, DAG.getNode(ISD::BSWAP,
2715 getValue(I.getOperand(1)).getValueType(),
2716 getValue(I.getOperand(1))));
2717 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002718 case Intrinsic::cttz: {
2719 SDOperand Arg = getValue(I.getOperand(1));
2720 MVT::ValueType Ty = Arg.getValueType();
2721 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
2722 if (Ty < MVT::i32)
2723 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2724 else if (Ty > MVT::i32)
2725 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2726 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002727 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002728 }
2729 case Intrinsic::ctlz: {
2730 SDOperand Arg = getValue(I.getOperand(1));
2731 MVT::ValueType Ty = Arg.getValueType();
2732 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
2733 if (Ty < MVT::i32)
2734 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2735 else if (Ty > MVT::i32)
2736 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2737 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002738 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002739 }
2740 case Intrinsic::ctpop: {
2741 SDOperand Arg = getValue(I.getOperand(1));
2742 MVT::ValueType Ty = Arg.getValueType();
2743 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
2744 if (Ty < MVT::i32)
2745 result = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, result);
2746 else if (Ty > MVT::i32)
2747 result = DAG.getNode(ISD::TRUNCATE, MVT::i32, result);
2748 setValue(&I, result);
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002749 return 0;
Reid Spencer3a0843e2007-04-01 07:34:11 +00002750 }
Chris Lattnerb3266452006-01-13 02:50:02 +00002751 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002752 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002753 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2754 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002755 setValue(&I, Tmp);
2756 DAG.setRoot(Tmp.getValue(1));
2757 return 0;
2758 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002759 case Intrinsic::stackrestore: {
2760 SDOperand Tmp = getValue(I.getOperand(1));
2761 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002762 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002763 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002764 case Intrinsic::prefetch:
2765 // FIXME: Currently discarding prefetches.
2766 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002767 }
2768}
2769
2770
Jim Laskey31fef782007-02-23 21:45:01 +00002771void SelectionDAGLowering::LowerCallTo(Instruction &I,
2772 const Type *CalledValueTy,
2773 unsigned CallingConv,
2774 bool IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002775 SDOperand Callee, unsigned OpIdx) {
Jim Laskey31fef782007-02-23 21:45:01 +00002776 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey504e9942007-02-22 15:38:06 +00002777 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Reid Spencer71b79e32007-04-09 06:17:21 +00002778 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Jim Laskey504e9942007-02-22 15:38:06 +00002779
2780 TargetLowering::ArgListTy Args;
2781 TargetLowering::ArgListEntry Entry;
2782 Args.reserve(I.getNumOperands());
2783 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2784 Value *Arg = I.getOperand(i);
2785 SDOperand ArgNode = getValue(Arg);
2786 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Reid Spencera472f662007-04-11 02:44:20 +00002787 Entry.isSExt = Attrs && Attrs->paramHasAttr(i, ParamAttr::SExt);
2788 Entry.isZExt = Attrs && Attrs->paramHasAttr(i, ParamAttr::ZExt);
2789 Entry.isInReg = Attrs && Attrs->paramHasAttr(i, ParamAttr::InReg);
2790 Entry.isSRet = Attrs && Attrs->paramHasAttr(i, ParamAttr::StructRet);
Jim Laskey504e9942007-02-22 15:38:06 +00002791 Args.push_back(Entry);
2792 }
2793
2794 std::pair<SDOperand,SDOperand> Result =
2795 TLI.LowerCallTo(getRoot(), I.getType(),
Reid Spencera472f662007-04-11 02:44:20 +00002796 Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt),
Jim Laskey31fef782007-02-23 21:45:01 +00002797 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey504e9942007-02-22 15:38:06 +00002798 Callee, Args, DAG);
2799 if (I.getType() != Type::VoidTy)
2800 setValue(&I, Result.first);
2801 DAG.setRoot(Result.second);
2802}
2803
2804
Chris Lattner7a60d912005-01-07 07:47:53 +00002805void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002806 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002807 if (Function *F = I.getCalledFunction()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00002808 if (F->isDeclaration())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002809 if (unsigned IID = F->getIntrinsicID()) {
2810 RenameFn = visitIntrinsicCall(I, IID);
2811 if (!RenameFn)
2812 return;
2813 } else { // Not an LLVM intrinsic.
2814 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002815 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2816 if (I.getNumOperands() == 3 && // Basic sanity checks.
2817 I.getOperand(1)->getType()->isFloatingPoint() &&
2818 I.getType() == I.getOperand(1)->getType() &&
2819 I.getType() == I.getOperand(2)->getType()) {
2820 SDOperand LHS = getValue(I.getOperand(1));
2821 SDOperand RHS = getValue(I.getOperand(2));
2822 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2823 LHS, RHS));
2824 return;
2825 }
2826 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002827 if (I.getNumOperands() == 2 && // Basic sanity checks.
2828 I.getOperand(1)->getType()->isFloatingPoint() &&
2829 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002830 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002831 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2832 return;
2833 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002834 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002835 if (I.getNumOperands() == 2 && // Basic sanity checks.
2836 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002837 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002838 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002839 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2840 return;
2841 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002842 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002843 if (I.getNumOperands() == 2 && // Basic sanity checks.
2844 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002845 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002846 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002847 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2848 return;
2849 }
2850 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002851 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002852 } else if (isa<InlineAsm>(I.getOperand(0))) {
2853 visitInlineAsm(I);
2854 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002855 }
Misha Brukman835702a2005-04-21 22:36:52 +00002856
Chris Lattner18d2b342005-01-08 22:48:57 +00002857 SDOperand Callee;
2858 if (!RenameFn)
2859 Callee = getValue(I.getOperand(0));
2860 else
2861 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Jim Laskey504e9942007-02-22 15:38:06 +00002862
Jim Laskey31fef782007-02-23 21:45:01 +00002863 LowerCallTo(I, I.getCalledValue()->getType(),
2864 I.getCallingConv(),
2865 I.isTailCall(),
2866 Callee,
2867 1);
Chris Lattner7a60d912005-01-07 07:47:53 +00002868}
2869
Jim Laskey504e9942007-02-22 15:38:06 +00002870
Chris Lattner6f87d182006-02-22 22:37:12 +00002871SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002872 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002873 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2874 Chain = Val.getValue(1);
2875 Flag = Val.getValue(2);
2876
2877 // If the result was expanded, copy from the top part.
2878 if (Regs.size() > 1) {
2879 assert(Regs.size() == 2 &&
2880 "Cannot expand to more than 2 elts yet!");
2881 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002882 Chain = Hi.getValue(1);
2883 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002884 if (DAG.getTargetLoweringInfo().isLittleEndian())
2885 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2886 else
2887 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002888 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002889
Chris Lattner705948d2006-06-08 18:22:48 +00002890 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002891 // appropriate type.
2892 if (RegVT == ValueVT)
2893 return Val;
2894
Chris Lattner77f04792007-03-25 05:00:54 +00002895 if (MVT::isVector(RegVT)) {
2896 assert(ValueVT == MVT::Vector && "Unknown vector conversion!");
2897 return DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
2898 DAG.getConstant(MVT::getVectorNumElements(RegVT),
2899 MVT::i32),
2900 DAG.getValueType(MVT::getVectorBaseType(RegVT)));
2901 }
2902
Chris Lattner705948d2006-06-08 18:22:48 +00002903 if (MVT::isInteger(RegVT)) {
2904 if (ValueVT < RegVT)
2905 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2906 else
2907 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002908 }
Chris Lattner77f04792007-03-25 05:00:54 +00002909
2910 assert(MVT::isFloatingPoint(RegVT) && MVT::isFloatingPoint(ValueVT));
2911 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002912}
2913
Chris Lattner571d9642006-02-23 19:21:04 +00002914/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2915/// specified value into the registers specified by this object. This uses
2916/// Chain/Flag as the input and updates them for the output Chain/Flag.
2917void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002918 SDOperand &Chain, SDOperand &Flag,
2919 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002920 if (Regs.size() == 1) {
2921 // If there is a single register and the types differ, this must be
2922 // a promotion.
2923 if (RegVT != ValueVT) {
Chris Lattner77f04792007-03-25 05:00:54 +00002924 if (MVT::isVector(RegVT)) {
2925 assert(Val.getValueType() == MVT::Vector &&"Not a vector-vector cast?");
2926 Val = DAG.getNode(ISD::VBIT_CONVERT, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002927 } else if (MVT::isInteger(RegVT) && MVT::isInteger(Val.getValueType())) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002928 if (RegVT < ValueVT)
2929 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2930 else
2931 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002932 } else if (MVT::isFloatingPoint(RegVT) &&
2933 MVT::isFloatingPoint(Val.getValueType())) {
Chris Lattner571d9642006-02-23 19:21:04 +00002934 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
Chris Lattner7b2decf2007-04-09 05:31:20 +00002935 } else if (MVT::getSizeInBits(RegVT) ==
2936 MVT::getSizeInBits(Val.getValueType())) {
2937 Val = DAG.getNode(ISD::BIT_CONVERT, RegVT, Val);
2938 } else {
2939 assert(0 && "Unknown mismatch!");
2940 }
Chris Lattner571d9642006-02-23 19:21:04 +00002941 }
2942 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2943 Flag = Chain.getValue(1);
2944 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002945 std::vector<unsigned> R(Regs);
2946 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2947 std::reverse(R.begin(), R.end());
2948
2949 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002950 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002951 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002952 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002953 Flag = Chain.getValue(1);
2954 }
2955 }
2956}
Chris Lattner6f87d182006-02-22 22:37:12 +00002957
Chris Lattner571d9642006-02-23 19:21:04 +00002958/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2959/// operand list. This adds the code marker and includes the number of
2960/// values added into it.
2961void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002962 std::vector<SDOperand> &Ops) const {
Chris Lattnerb49917d2007-04-09 00:33:58 +00002963 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
2964 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner571d9642006-02-23 19:21:04 +00002965 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2966 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2967}
Chris Lattner6f87d182006-02-22 22:37:12 +00002968
2969/// isAllocatableRegister - If the specified register is safe to allocate,
2970/// i.e. it isn't a stack pointer or some other special register, return the
2971/// register class for the register. Otherwise, return null.
2972static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002973isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2974 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002975 MVT::ValueType FoundVT = MVT::Other;
2976 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002977 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2978 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002979 MVT::ValueType ThisVT = MVT::Other;
2980
Chris Lattnerb1124f32006-02-22 23:09:03 +00002981 const TargetRegisterClass *RC = *RCI;
2982 // If none of the the value types for this register class are valid, we
2983 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002984 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2985 I != E; ++I) {
2986 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002987 // If we have already found this register in a different register class,
2988 // choose the one with the largest VT specified. For example, on
2989 // PowerPC, we favor f64 register classes over f32.
2990 if (FoundVT == MVT::Other ||
2991 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2992 ThisVT = *I;
2993 break;
2994 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002995 }
2996 }
2997
Chris Lattnerbec582f2006-04-02 00:24:45 +00002998 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002999
Chris Lattner6f87d182006-02-22 22:37:12 +00003000 // NOTE: This isn't ideal. In particular, this might allocate the
3001 // frame pointer in functions that need it (due to them not being taken
3002 // out of allocation, because a variable sized allocation hasn't been seen
3003 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00003004 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3005 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00003006 if (*I == Reg) {
3007 // We found a matching register class. Keep looking at others in case
3008 // we find one with larger registers that this physreg is also in.
3009 FoundRC = RC;
3010 FoundVT = ThisVT;
3011 break;
3012 }
Chris Lattner1558fc62006-02-01 18:59:47 +00003013 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00003014 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00003015}
3016
Chris Lattner1558fc62006-02-01 18:59:47 +00003017
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003018namespace {
3019/// AsmOperandInfo - This contains information for each constraint that we are
3020/// lowering.
3021struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
3022 /// ConstraintCode - This contains the actual string for the code, like "m".
3023 std::string ConstraintCode;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003024
3025 /// ConstraintType - Information about the constraint code, e.g. Register,
3026 /// RegisterClass, Memory, Other, Unknown.
3027 TargetLowering::ConstraintType ConstraintType;
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003028
3029 /// CallOperand/CallOperandval - If this is the result output operand or a
3030 /// clobber, this is null, otherwise it is the incoming operand to the
3031 /// CallInst. This gets modified as the asm is processed.
3032 SDOperand CallOperand;
3033 Value *CallOperandVal;
3034
3035 /// ConstraintVT - The ValueType for the operand value.
3036 MVT::ValueType ConstraintVT;
3037
3038 AsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Chris Lattnerb2e55562007-04-28 21:01:43 +00003039 : InlineAsm::ConstraintInfo(info),
3040 ConstraintType(TargetLowering::C_Unknown),
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003041 CallOperand(0,0), CallOperandVal(0), ConstraintVT(MVT::Other) {
3042 }
Chris Lattneref073322007-04-30 17:16:27 +00003043
3044 void ComputeConstraintToUse(const TargetLowering &TLI);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003045};
3046} // end anon namespace.
Chris Lattner6f87d182006-02-22 22:37:12 +00003047
Chris Lattneref073322007-04-30 17:16:27 +00003048/// getConstraintGenerality - Return an integer indicating how general CT is.
3049static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
3050 switch (CT) {
3051 default: assert(0 && "Unknown constraint type!");
3052 case TargetLowering::C_Other:
3053 case TargetLowering::C_Unknown:
3054 return 0;
3055 case TargetLowering::C_Register:
3056 return 1;
3057 case TargetLowering::C_RegisterClass:
3058 return 2;
3059 case TargetLowering::C_Memory:
3060 return 3;
3061 }
3062}
3063
3064void AsmOperandInfo::ComputeConstraintToUse(const TargetLowering &TLI) {
3065 assert(!Codes.empty() && "Must have at least one constraint");
3066
3067 std::string *Current = &Codes[0];
3068 TargetLowering::ConstraintType CurType = TLI.getConstraintType(*Current);
3069 if (Codes.size() == 1) { // Single-letter constraints ('r') are very common.
3070 ConstraintCode = *Current;
3071 ConstraintType = CurType;
3072 return;
3073 }
3074
3075 unsigned CurGenerality = getConstraintGenerality(CurType);
3076
3077 // If we have multiple constraints, try to pick the most general one ahead
3078 // of time. This isn't a wonderful solution, but handles common cases.
3079 for (unsigned j = 1, e = Codes.size(); j != e; ++j) {
3080 TargetLowering::ConstraintType ThisType = TLI.getConstraintType(Codes[j]);
3081 unsigned ThisGenerality = getConstraintGenerality(ThisType);
3082 if (ThisGenerality > CurGenerality) {
3083 // This constraint letter is more general than the previous one,
3084 // use it.
3085 CurType = ThisType;
3086 Current = &Codes[j];
3087 CurGenerality = ThisGenerality;
3088 }
3089 }
3090
3091 ConstraintCode = *Current;
3092 ConstraintType = CurType;
3093}
3094
3095
Chris Lattner4333f8b2007-04-30 17:29:31 +00003096RegsForValue SelectionDAGLowering::
3097GetRegistersForValue(AsmOperandInfo &OpInfo, bool isOutReg, bool isInReg,
3098 std::set<unsigned> &OutputRegs,
3099 std::set<unsigned> &InputRegs) {
3100 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3101 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,OpInfo.ConstraintVT);
3102 std::vector<unsigned> Regs;
3103
3104 unsigned NumRegs = 1;
3105 if (OpInfo.ConstraintVT != MVT::Other)
3106 NumRegs = TLI.getNumElements(OpInfo.ConstraintVT);
3107 MVT::ValueType RegVT;
3108 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3109
3110 MachineFunction &MF = DAG.getMachineFunction();
3111
3112 // If this is a constraint for a specific physical register, like {r17},
3113 // assign it now.
3114 if (PhysReg.first) {
3115 if (OpInfo.ConstraintVT == MVT::Other)
3116 ValueVT = *PhysReg.second->vt_begin();
3117
3118 // Get the actual register value type. This is important, because the user
3119 // may have asked for (e.g.) the AX register in i32 type. We need to
3120 // remember that AX is actually i16 to get the right extension.
3121 RegVT = *PhysReg.second->vt_begin();
3122
3123 // This is a explicit reference to a physical register.
3124 Regs.push_back(PhysReg.first);
3125
3126 // If this is an expanded reference, add the rest of the regs to Regs.
3127 if (NumRegs != 1) {
3128 TargetRegisterClass::iterator I = PhysReg.second->begin();
3129 TargetRegisterClass::iterator E = PhysReg.second->end();
3130 for (; *I != PhysReg.first; ++I)
3131 assert(I != E && "Didn't find reg!");
3132
3133 // Already added the first reg.
3134 --NumRegs; ++I;
3135 for (; NumRegs; --NumRegs, ++I) {
3136 assert(I != E && "Ran out of registers to allocate!");
3137 Regs.push_back(*I);
3138 }
3139 }
3140 return RegsForValue(Regs, RegVT, ValueVT);
3141 }
3142
3143 // Otherwise, if this was a reference to an LLVM register class, create vregs
3144 // for this reference.
3145 std::vector<unsigned> RegClassRegs;
3146 if (PhysReg.second) {
3147 // If this is an early clobber or tied register, our regalloc doesn't know
3148 // how to maintain the constraint. If it isn't, go ahead and create vreg
3149 // and let the regalloc do the right thing.
3150 if (!isOutReg || !isInReg) {
3151 RegVT = *PhysReg.second->vt_begin();
3152
3153 if (OpInfo.ConstraintVT == MVT::Other)
3154 ValueVT = RegVT;
3155
3156 // Create the appropriate number of virtual registers.
3157 SSARegMap *RegMap = MF.getSSARegMap();
3158 for (; NumRegs; --NumRegs)
3159 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
3160
3161 return RegsForValue(Regs, RegVT, ValueVT);
3162 }
3163
3164 // Otherwise, we can't allocate it. Let the code below figure out how to
3165 // maintain these constraints.
3166 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3167
3168 } else {
3169 // This is a reference to a register class that doesn't directly correspond
3170 // to an LLVM register class. Allocate NumRegs consecutive, available,
3171 // registers from the class.
3172 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3173 OpInfo.ConstraintVT);
3174 }
3175
3176 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
3177 unsigned NumAllocated = 0;
3178 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3179 unsigned Reg = RegClassRegs[i];
3180 // See if this register is available.
3181 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3182 (isInReg && InputRegs.count(Reg))) { // Already used.
3183 // Make sure we find consecutive registers.
3184 NumAllocated = 0;
3185 continue;
3186 }
3187
3188 // Check to see if this register is allocatable (i.e. don't give out the
3189 // stack pointer).
3190 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
3191 if (!RC) {
3192 // Make sure we find consecutive registers.
3193 NumAllocated = 0;
3194 continue;
3195 }
3196
3197 // Okay, this register is good, we can use it.
3198 ++NumAllocated;
3199
3200 // If we allocated enough consecutive registers, succeed.
3201 if (NumAllocated == NumRegs) {
3202 unsigned RegStart = (i-NumAllocated)+1;
3203 unsigned RegEnd = i+1;
3204 // Mark all of the allocated registers used.
3205 for (unsigned i = RegStart; i != RegEnd; ++i) {
3206 unsigned Reg = RegClassRegs[i];
3207 Regs.push_back(Reg);
3208 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
3209 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
3210 }
3211
3212 return RegsForValue(Regs, *RC->vt_begin(), OpInfo.ConstraintVT);
3213 }
3214 }
3215
3216 // Otherwise, we couldn't allocate enough registers for this.
3217 return RegsForValue();
3218}
3219
3220
Chris Lattner476e67b2006-01-26 22:24:51 +00003221/// visitInlineAsm - Handle a call to an InlineAsm object.
3222///
3223void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
3224 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
Chris Lattner476e67b2006-01-26 22:24:51 +00003225
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003226 /// ConstraintOperands - Information about all of the constraints.
3227 std::vector<AsmOperandInfo> ConstraintOperands;
Chris Lattner476e67b2006-01-26 22:24:51 +00003228
3229 SDOperand Chain = getRoot();
3230 SDOperand Flag;
3231
Chris Lattner1558fc62006-02-01 18:59:47 +00003232 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00003233
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003234 // Do a prepass over the constraints, canonicalizing them, and building up the
3235 // ConstraintOperands list.
3236 std::vector<InlineAsm::ConstraintInfo>
3237 ConstraintInfos = IA->ParseConstraints();
3238 unsigned OpNo = 1;
3239 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3240 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
3241 AsmOperandInfo &OpInfo = ConstraintOperands.back();
3242
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003243 MVT::ValueType OpVT = MVT::Other;
3244
3245 // Compute the value type for each operand.
3246 switch (OpInfo.Type) {
Chris Lattner7ad77df2006-02-22 00:56:39 +00003247 case InlineAsm::isOutput:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003248 if (!OpInfo.isIndirect) {
3249 // The return value of the call is this value. As such, there is no
3250 // corresponding argument.
Chris Lattner7ad77df2006-02-22 00:56:39 +00003251 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
3252 OpVT = TLI.getValueType(I.getType());
3253 } else {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003254 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner7ad77df2006-02-22 00:56:39 +00003255 }
3256 break;
3257 case InlineAsm::isInput:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003258 OpInfo.CallOperandVal = I.getOperand(OpNo++);
Chris Lattner7ad77df2006-02-22 00:56:39 +00003259 break;
3260 case InlineAsm::isClobber:
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003261 // Nothing to do.
Chris Lattner7ad77df2006-02-22 00:56:39 +00003262 break;
3263 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00003264
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003265 // If this is an input or an indirect output, process the call argument.
3266 if (OpInfo.CallOperandVal) {
3267 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3268 const Type *OpTy = OpInfo.CallOperandVal->getType();
Chris Lattner412d61a2007-04-29 18:58:03 +00003269 // If this is an indirect operand, the operand is a pointer to the
3270 // accessed type.
3271 if (OpInfo.isIndirect)
3272 OpTy = cast<PointerType>(OpTy)->getElementType();
3273
3274 // If OpTy is not a first-class value, it may be a struct/union that we
3275 // can tile with integers.
3276 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3277 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3278 switch (BitSize) {
3279 default: break;
3280 case 1:
3281 case 8:
3282 case 16:
3283 case 32:
3284 case 64:
3285 OpTy = IntegerType::get(BitSize);
3286 break;
3287 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003288 }
Chris Lattner412d61a2007-04-29 18:58:03 +00003289
3290 OpVT = TLI.getValueType(OpTy, true);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003291 }
3292
3293 OpInfo.ConstraintVT = OpVT;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003294
Chris Lattneref073322007-04-30 17:16:27 +00003295 // Compute the constraint code and ConstraintType to use.
3296 OpInfo.ComputeConstraintToUse(TLI);
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003297
Chris Lattner401d8db2007-04-28 21:12:06 +00003298
3299 // If this is a memory input, and if the operand is not indirect, do what we
3300 // need to to provide an address for the memory input.
3301 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3302 !OpInfo.isIndirect) {
3303 assert(OpInfo.Type == InlineAsm::isInput &&
3304 "Can only indirectify direct input operands!");
3305
3306 // Memory operands really want the address of the value. If we don't have
3307 // an indirect input, put it in the constpool if we can, otherwise spill
3308 // it to a stack slot.
3309
3310 // If the operand is a float, integer, or vector constant, spill to a
3311 // constant pool entry to get its address.
3312 Value *OpVal = OpInfo.CallOperandVal;
3313 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3314 isa<ConstantVector>(OpVal)) {
3315 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3316 TLI.getPointerTy());
3317 } else {
3318 // Otherwise, create a stack slot and emit a store to it before the
3319 // asm.
3320 const Type *Ty = OpVal->getType();
3321 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
3322 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3323 MachineFunction &MF = DAG.getMachineFunction();
3324 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3325 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3326 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3327 OpInfo.CallOperand = StackSlot;
3328 }
3329
3330 // There is no longer a Value* corresponding to this operand.
3331 OpInfo.CallOperandVal = 0;
3332 // It is now an indirect operand.
3333 OpInfo.isIndirect = true;
3334 }
3335
3336
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003337 if (TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode, OpVT).first ==0)
Chris Lattner6f87d182006-02-22 22:37:12 +00003338 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00003339
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003340 // For GCC register classes where we don't have a direct match, we fully
3341 // assign registers at isel time. This is not optimal, but works.
3342
Chris Lattner6f87d182006-02-22 22:37:12 +00003343 // Build a list of regs that this operand uses. This always has a single
3344 // element for promoted/expanded operands.
Chris Lattner4333f8b2007-04-30 17:29:31 +00003345 RegsForValue Regs = GetRegistersForValue(OpInfo, false, false,
Chris Lattner6f87d182006-02-22 22:37:12 +00003346 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00003347
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003348 switch (OpInfo.Type) {
Chris Lattner1558fc62006-02-01 18:59:47 +00003349 case InlineAsm::isOutput:
3350 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00003351 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00003352 // If this is an early-clobber output, it cannot be assigned to the same
3353 // value as the input reg.
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003354 if (OpInfo.isEarlyClobber || OpInfo.hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00003355 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00003356 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00003357 case InlineAsm::isInput:
3358 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00003359 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00003360 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00003361 case InlineAsm::isClobber:
3362 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00003363 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
3364 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00003365 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00003366 }
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003367 }
3368
3369 ConstraintInfos.clear();
3370
3371
3372 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3373 std::vector<SDOperand> AsmNodeOperands;
3374 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3375 AsmNodeOperands.push_back(
3376 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3377
Chris Lattner3a5ed552006-02-01 01:28:23 +00003378
Chris Lattner5c79f982006-02-21 23:12:12 +00003379 // Loop over all of the inputs, copying the operand values into the
3380 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00003381 RegsForValue RetValRegs;
Chris Lattner5c79f982006-02-21 23:12:12 +00003382
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003383 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3384 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3385
3386 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
3387 AsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner7ad77df2006-02-22 00:56:39 +00003388
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003389 switch (OpInfo.Type) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00003390 case InlineAsm::isOutput: {
Chris Lattnerde339fa2007-04-28 21:03:16 +00003391 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3392 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerd102ed02007-04-28 06:08:13 +00003393 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner401d8db2007-04-28 21:12:06 +00003394 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner9fed5b62006-02-27 23:45:39 +00003395
Chris Lattner9fed5b62006-02-27 23:45:39 +00003396 // Add information to the INLINEASM node to know about this output.
3397 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3398 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
Chris Lattner401d8db2007-04-28 21:12:06 +00003399 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner9fed5b62006-02-27 23:45:39 +00003400 break;
3401 }
3402
Chris Lattnerb2e55562007-04-28 21:01:43 +00003403 // Otherwise, this is a register or register class output.
Chris Lattner9fed5b62006-02-27 23:45:39 +00003404
Chris Lattner6f87d182006-02-22 22:37:12 +00003405 // If this is an early-clobber output, or if there is an input
3406 // constraint that matches this, we need to reserve the input register
3407 // so no other inputs allocate to it.
3408 bool UsesInputRegister = false;
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003409 if (OpInfo.isEarlyClobber || OpInfo.hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00003410 UsesInputRegister = true;
3411
3412 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00003413 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00003414 RegsForValue Regs =
Chris Lattner4333f8b2007-04-30 17:29:31 +00003415 GetRegistersForValue(OpInfo, true, UsesInputRegister,
Chris Lattner6f87d182006-02-22 22:37:12 +00003416 OutputRegs, InputRegs);
Chris Lattner968f8032006-10-31 07:33:13 +00003417 if (Regs.Regs.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003418 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003419 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner968f8032006-10-31 07:33:13 +00003420 exit(1);
3421 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00003422
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003423 if (!OpInfo.isIndirect) {
3424 // This is the result value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00003425 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00003426 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00003427 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00003428 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00003429 } else {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003430 IndirectStoresToEmit.push_back(std::make_pair(Regs,
3431 OpInfo.CallOperandVal));
Chris Lattner3a5ed552006-02-01 01:28:23 +00003432 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003433
3434 // Add information to the INLINEASM node to know that this register is
3435 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00003436 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003437 break;
3438 }
3439 case InlineAsm::isInput: {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003440 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner65ad53f2006-02-04 02:16:44 +00003441
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003442 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner7f5880b2006-02-02 00:25:23 +00003443 // If this is required to match an output register we have already set,
3444 // just use its register.
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003445 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00003446
Chris Lattner571d9642006-02-23 19:21:04 +00003447 // Scan until we find the definition we already emitted of this operand.
3448 // When we find it, create a RegsForValue operand.
3449 unsigned CurOp = 2; // The first operand.
3450 for (; OperandNo; --OperandNo) {
3451 // Advance to the next operand.
3452 unsigned NumOps =
3453 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00003454 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3455 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00003456 "Skipped past definitions?");
3457 CurOp += (NumOps>>3)+1;
3458 }
3459
3460 unsigned NumOps =
3461 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnere3eeb242007-02-01 01:21:12 +00003462 if ((NumOps & 7) == 2 /*REGDEF*/) {
3463 // Add NumOps>>3 registers to MatchedRegs.
3464 RegsForValue MatchedRegs;
3465 MatchedRegs.ValueVT = InOperandVal.getValueType();
3466 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
3467 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
3468 unsigned Reg =
3469 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
3470 MatchedRegs.Regs.push_back(Reg);
3471 }
Chris Lattner571d9642006-02-23 19:21:04 +00003472
Chris Lattnere3eeb242007-02-01 01:21:12 +00003473 // Use the produced MatchedRegs object to
3474 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
3475 TLI.getPointerTy());
3476 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
3477 break;
3478 } else {
3479 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
3480 assert(0 && "matching constraints for memory operands unimp");
Chris Lattner571d9642006-02-23 19:21:04 +00003481 }
Chris Lattner7f5880b2006-02-02 00:25:23 +00003482 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003483
Chris Lattnerb2e55562007-04-28 21:01:43 +00003484 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003485 assert(!OpInfo.isIndirect &&
Chris Lattner1deacd62007-04-28 06:42:38 +00003486 "Don't know how to handle indirect other inputs yet!");
3487
Chris Lattner6f043b92006-10-31 19:41:18 +00003488 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003489 OpInfo.ConstraintCode[0],
3490 DAG);
Chris Lattner6f043b92006-10-31 19:41:18 +00003491 if (!InOperandVal.Val) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003492 cerr << "Invalid operand for inline asm constraint '"
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003493 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner6f043b92006-10-31 19:41:18 +00003494 exit(1);
3495 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00003496
3497 // Add information to the INLINEASM node to know about this input.
3498 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
3499 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3500 AsmNodeOperands.push_back(InOperandVal);
3501 break;
Chris Lattnerb2e55562007-04-28 21:01:43 +00003502 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner401d8db2007-04-28 21:12:06 +00003503 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner1deacd62007-04-28 06:42:38 +00003504 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
3505 "Memory operands expect pointer values");
3506
Chris Lattner7ef7a642006-02-24 01:11:24 +00003507 // Add information to the INLINEASM node to know about this input.
3508 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
3509 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
3510 AsmNodeOperands.push_back(InOperandVal);
3511 break;
3512 }
3513
Chris Lattnerb2e55562007-04-28 21:01:43 +00003514 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
3515 OpInfo.ConstraintType == TargetLowering::C_Register) &&
3516 "Unknown constraint type!");
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003517 assert(!OpInfo.isIndirect &&
Chris Lattner1deacd62007-04-28 06:42:38 +00003518 "Don't know how to handle indirect register inputs yet!");
Chris Lattner7ef7a642006-02-24 01:11:24 +00003519
3520 // Copy the input into the appropriate registers.
3521 RegsForValue InRegs =
Chris Lattner4333f8b2007-04-30 17:29:31 +00003522 GetRegistersForValue(OpInfo, false, true, OutputRegs, InputRegs);
Chris Lattner7ef7a642006-02-24 01:11:24 +00003523 // FIXME: should be match fail.
3524 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
3525
Evan Chengef9e07d2006-06-15 08:11:54 +00003526 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00003527
3528 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003529 break;
3530 }
Chris Lattner571d9642006-02-23 19:21:04 +00003531 case InlineAsm::isClobber: {
3532 RegsForValue ClobberedRegs =
Chris Lattner4333f8b2007-04-30 17:29:31 +00003533 GetRegistersForValue(OpInfo, false,
3534 false, OutputRegs, InputRegs);
Chris Lattner571d9642006-02-23 19:21:04 +00003535 // Add the clobbered value to the operand list, so that the register
3536 // allocator is aware that the physreg got clobbered.
3537 if (!ClobberedRegs.Regs.empty())
3538 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00003539 break;
3540 }
Chris Lattner571d9642006-02-23 19:21:04 +00003541 }
Chris Lattner2e56e892006-01-31 02:03:41 +00003542 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003543
3544 // Finish up input operands.
3545 AsmNodeOperands[0] = Chain;
3546 if (Flag.Val) AsmNodeOperands.push_back(Flag);
3547
Chris Lattnerbd887772006-08-14 23:53:35 +00003548 Chain = DAG.getNode(ISD::INLINEASM,
3549 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003550 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003551 Flag = Chain.getValue(1);
3552
Chris Lattner2e56e892006-01-31 02:03:41 +00003553 // If this asm returns a register value, copy the result from that register
3554 // and set it as the value of the call.
Chris Lattner51114992007-04-12 06:00:20 +00003555 if (!RetValRegs.Regs.empty()) {
3556 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, Flag);
3557
3558 // If the result of the inline asm is a vector, it may have the wrong
3559 // width/num elts. Make sure to convert it to the right type with
3560 // vbit_convert.
3561 if (Val.getValueType() == MVT::Vector) {
3562 const VectorType *VTy = cast<VectorType>(I.getType());
3563 unsigned DesiredNumElts = VTy->getNumElements();
3564 MVT::ValueType DesiredEltVT = TLI.getValueType(VTy->getElementType());
3565
3566 Val = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Val,
3567 DAG.getConstant(DesiredNumElts, MVT::i32),
3568 DAG.getValueType(DesiredEltVT));
3569 }
3570
3571 setValue(&I, Val);
3572 }
Chris Lattner476e67b2006-01-26 22:24:51 +00003573
Chris Lattner2e56e892006-01-31 02:03:41 +00003574 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
3575
3576 // Process indirect outputs, first output all of the flagged copies out of
3577 // physregs.
3578 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00003579 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00003580 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00003581 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
3582 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00003583 }
3584
3585 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003586 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00003587 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattnerd7e3b6c2007-04-28 20:49:53 +00003588 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00003589 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00003590 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00003591 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003592 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3593 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00003594 DAG.setRoot(Chain);
3595}
3596
3597
Chris Lattner7a60d912005-01-07 07:47:53 +00003598void SelectionDAGLowering::visitMalloc(MallocInst &I) {
3599 SDOperand Src = getValue(I.getOperand(0));
3600
3601 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00003602
3603 if (IntPtr < Src.getValueType())
3604 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
3605 else if (IntPtr > Src.getValueType())
3606 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00003607
3608 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00003609 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00003610 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
3611 Src, getIntPtrConstant(ElementSize));
3612
Reid Spencere63b6512006-12-31 05:55:36 +00003613 TargetLowering::ArgListTy Args;
3614 TargetLowering::ArgListEntry Entry;
3615 Entry.Node = Src;
3616 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003617 Args.push_back(Entry);
Chris Lattner1f45cd72005-01-08 19:26:18 +00003618
3619 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003620 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003621 DAG.getExternalSymbol("malloc", IntPtr),
3622 Args, DAG);
3623 setValue(&I, Result.first); // Pointers always fit in registers
3624 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003625}
3626
3627void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencere63b6512006-12-31 05:55:36 +00003628 TargetLowering::ArgListTy Args;
3629 TargetLowering::ArgListEntry Entry;
3630 Entry.Node = getValue(I.getOperand(0));
3631 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencere63b6512006-12-31 05:55:36 +00003632 Args.push_back(Entry);
Chris Lattner7a60d912005-01-07 07:47:53 +00003633 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00003634 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00003635 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00003636 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3637 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003638}
3639
Chris Lattner13d7c252005-08-26 20:54:47 +00003640// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3641// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3642// instructions are special in various ways, which require special support to
3643// insert. The specified MachineInstr is created but not inserted into any
3644// basic blocks, and the scheduler passes ownership of it to this method.
3645MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3646 MachineBasicBlock *MBB) {
Bill Wendling22e978a2006-12-07 20:04:42 +00003647 cerr << "If a target marks an instruction with "
3648 << "'usesCustomDAGSchedInserter', it must implement "
3649 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner13d7c252005-08-26 20:54:47 +00003650 abort();
3651 return 0;
3652}
3653
Chris Lattner58cfd792005-01-09 00:00:49 +00003654void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003655 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3656 getValue(I.getOperand(1)),
3657 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00003658}
3659
3660void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003661 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3662 getValue(I.getOperand(0)),
3663 DAG.getSrcValue(I.getOperand(0)));
3664 setValue(&I, V);
3665 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00003666}
3667
3668void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003669 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3670 getValue(I.getOperand(1)),
3671 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003672}
3673
3674void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00003675 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3676 getValue(I.getOperand(1)),
3677 getValue(I.getOperand(2)),
3678 DAG.getSrcValue(I.getOperand(1)),
3679 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00003680}
3681
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003682/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3683/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3684static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3685 unsigned &i, SelectionDAG &DAG,
3686 TargetLowering &TLI) {
3687 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3688 return SDOperand(Arg, i++);
3689
3690 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3691 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3692 if (NumVals == 1) {
3693 return DAG.getNode(ISD::BIT_CONVERT, VT,
3694 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3695 } else if (NumVals == 2) {
3696 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3697 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3698 if (!TLI.isLittleEndian())
3699 std::swap(Lo, Hi);
3700 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3701 } else {
3702 // Value scalarized into many values. Unimp for now.
3703 assert(0 && "Cannot expand i64 -> i16 yet!");
3704 }
3705 return SDOperand();
3706}
3707
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003708/// TargetLowering::LowerArguments - This is the default LowerArguments
3709/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00003710/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3711/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003712std::vector<SDOperand>
3713TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003714 const FunctionType *FTy = F.getFunctionType();
Reid Spencer71b79e32007-04-09 06:17:21 +00003715 const ParamAttrsList *Attrs = FTy->getParamAttrs();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003716 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3717 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00003718 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003719 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3720 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3721
3722 // Add one result value for each formal argument.
3723 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov06f7d4b2007-01-28 18:01:49 +00003724 unsigned j = 1;
Anton Korobeynikov9fa38392007-01-28 16:04:40 +00003725 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3726 I != E; ++I, ++j) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003727 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003728 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003729 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003730 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003731
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003732 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3733 // that is zero extended!
Reid Spencera472f662007-04-11 02:44:20 +00003734 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::ZExt))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003735 Flags &= ~(ISD::ParamFlags::SExt);
Reid Spencera472f662007-04-11 02:44:20 +00003736 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::SExt))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003737 Flags |= ISD::ParamFlags::SExt;
Reid Spencera472f662007-04-11 02:44:20 +00003738 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::InReg))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003739 Flags |= ISD::ParamFlags::InReg;
Reid Spencera472f662007-04-11 02:44:20 +00003740 if (Attrs && Attrs->paramHasAttr(j, ParamAttr::StructRet))
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003741 Flags |= ISD::ParamFlags::StructReturn;
3742 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerab5d0ac2007-02-26 02:56:58 +00003743
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003744 switch (getTypeAction(VT)) {
3745 default: assert(0 && "Unknown type action!");
3746 case Legal:
3747 RetVals.push_back(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003748 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003749 break;
3750 case Promote:
3751 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003752 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003753 break;
3754 case Expand:
3755 if (VT != MVT::Vector) {
3756 // If this is a large integer, it needs to be broken up into small
3757 // integers. Figure out what the destination type is and how many small
3758 // integers it turns into.
Evan Cheng22cf8992006-12-13 20:57:08 +00003759 MVT::ValueType NVT = getTypeToExpandTo(VT);
3760 unsigned NumVals = getNumElements(VT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003761 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003762 RetVals.push_back(NVT);
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003763 // if it isn't first piece, alignment must be 1
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003764 if (i > 0)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003765 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3766 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003767 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3768 }
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003769 } else {
3770 // Otherwise, this is a vector type. We only support legal vectors
3771 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003772 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3773 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003774
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003775 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003776 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003777 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3778 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3779 RetVals.push_back(TVT);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003780 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003781 } else {
3782 assert(0 && "Don't support illegal by-val vector arguments yet!");
3783 }
3784 }
3785 break;
3786 }
3787 }
Evan Cheng9618df12006-04-25 23:03:35 +00003788
Chris Lattner3d826992006-05-16 06:45:34 +00003789 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003790
3791 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00003792 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3793 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003794 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00003795
3796 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003797
3798 // Set up the return result vector.
3799 Ops.clear();
3800 unsigned i = 0;
Reid Spencere63b6512006-12-31 05:55:36 +00003801 unsigned Idx = 1;
3802 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3803 ++I, ++Idx) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003804 MVT::ValueType VT = getValueType(I->getType());
3805
3806 switch (getTypeAction(VT)) {
3807 default: assert(0 && "Unknown type action!");
3808 case Legal:
3809 Ops.push_back(SDOperand(Result, i++));
3810 break;
3811 case Promote: {
3812 SDOperand Op(Result, i++);
3813 if (MVT::isInteger(VT)) {
Reid Spencera472f662007-04-11 02:44:20 +00003814 if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt))
Chris Lattner96035be2007-01-04 22:22:37 +00003815 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3816 DAG.getValueType(VT));
Reid Spencera472f662007-04-11 02:44:20 +00003817 else if (Attrs && Attrs->paramHasAttr(Idx, ParamAttr::ZExt))
Chris Lattner96035be2007-01-04 22:22:37 +00003818 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3819 DAG.getValueType(VT));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003820 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3821 } else {
3822 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3823 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3824 }
3825 Ops.push_back(Op);
3826 break;
3827 }
3828 case Expand:
3829 if (VT != MVT::Vector) {
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003830 // If this is a large integer or a floating point node that needs to be
3831 // expanded, it needs to be reassembled from small integers. Figure out
3832 // what the source elt type is and how many small integers it is.
3833 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003834 } else {
3835 // Otherwise, this is a vector type. We only support legal vectors
3836 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003837 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Chengd43c5c62006-04-28 05:25:15 +00003838 unsigned NumElems = PTy->getNumElements();
3839 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00003840
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003841 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003842 // type. If so, convert to the vector type.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003843 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00003844 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00003845 SDOperand N = SDOperand(Result, i++);
3846 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00003847 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3848 DAG.getConstant(NumElems, MVT::i32),
3849 DAG.getValueType(getValueType(EltTy)));
3850 Ops.push_back(N);
3851 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003852 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00003853 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00003854 }
3855 }
3856 break;
3857 }
3858 }
3859 return Ops;
3860}
3861
Chris Lattneraaa23d92006-05-16 22:53:20 +00003862
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003863/// ExpandScalarCallArgs - Recursively expand call argument node by
3864/// bit_converting it or extract a pair of elements from the larger node.
3865static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003866 unsigned Flags,
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003867 SmallVector<SDOperand, 32> &Ops,
3868 SelectionDAG &DAG,
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003869 TargetLowering &TLI,
3870 bool isFirst = true) {
3871
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003872 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venancioabde3cc2007-02-13 18:10:13 +00003873 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003874 if (!isFirst)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003875 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3876 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003877 Ops.push_back(Arg);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003878 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003879 return;
3880 }
3881
3882 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3883 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3884 if (NumVals == 1) {
3885 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003886 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003887 } else if (NumVals == 2) {
3888 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3889 DAG.getConstant(0, TLI.getPointerTy()));
3890 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3891 DAG.getConstant(1, TLI.getPointerTy()));
3892 if (!TLI.isLittleEndian())
3893 std::swap(Lo, Hi);
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003894 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3895 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003896 } else {
3897 // Value scalarized into many values. Unimp for now.
3898 assert(0 && "Cannot expand i64 -> i16 yet!");
3899 }
3900}
3901
Chris Lattneraaa23d92006-05-16 22:53:20 +00003902/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3903/// implementation, which just inserts an ISD::CALL node, which is later custom
3904/// lowered by the target to something concrete. FIXME: When all targets are
3905/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3906std::pair<SDOperand, SDOperand>
Reid Spencere63b6512006-12-31 05:55:36 +00003907TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3908 bool RetTyIsSigned, bool isVarArg,
Chris Lattneraaa23d92006-05-16 22:53:20 +00003909 unsigned CallingConv, bool isTailCall,
3910 SDOperand Callee,
3911 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00003912 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003913 Ops.push_back(Chain); // Op#0 - Chain
3914 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3915 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3916 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3917 Ops.push_back(Callee);
3918
3919 // Handle all of the outgoing arguments.
3920 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencere63b6512006-12-31 05:55:36 +00003921 MVT::ValueType VT = getValueType(Args[i].Ty);
3922 SDOperand Op = Args[i].Node;
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003923 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003924 unsigned OriginalAlignment =
Chris Lattner945e4372007-02-14 05:52:17 +00003925 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003926
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003927 if (Args[i].isSExt)
3928 Flags |= ISD::ParamFlags::SExt;
3929 if (Args[i].isZExt)
3930 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003931 if (Args[i].isInReg)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003932 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003933 if (Args[i].isSRet)
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003934 Flags |= ISD::ParamFlags::StructReturn;
3935 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikovf0b93162007-03-06 06:10:33 +00003936
Chris Lattneraaa23d92006-05-16 22:53:20 +00003937 switch (getTypeAction(VT)) {
3938 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio9956dcf2007-02-13 13:50:08 +00003939 case Legal:
Chris Lattneraaa23d92006-05-16 22:53:20 +00003940 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003941 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003942 break;
3943 case Promote:
3944 if (MVT::isInteger(VT)) {
Anton Korobeynikoved4b3032007-03-07 16:25:09 +00003945 unsigned ExtOp;
3946 if (Args[i].isSExt)
3947 ExtOp = ISD::SIGN_EXTEND;
3948 else if (Args[i].isZExt)
3949 ExtOp = ISD::ZERO_EXTEND;
3950 else
3951 ExtOp = ISD::ANY_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003952 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3953 } else {
3954 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3955 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3956 }
3957 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003958 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003959 break;
3960 case Expand:
3961 if (VT != MVT::Vector) {
3962 // If this is a large integer, it needs to be broken down into small
3963 // integers. Figure out what the source elt type is and how many small
3964 // integers it is.
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003965 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003966 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003967 // Otherwise, this is a vector type. We only support legal vectors
3968 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00003969 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003970 unsigned NumElems = PTy->getNumElements();
3971 const Type *EltTy = PTy->getElementType();
3972
3973 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00003974 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00003975 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00003976 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencer09575ba2007-02-15 03:39:18 +00003977 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner938155c2006-05-17 20:43:21 +00003978 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3979 Ops.push_back(Op);
Anton Korobeynikov037c8672007-01-28 13:31:35 +00003980 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00003981 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003982 assert(0 && "Don't support illegal by-val vector call args yet!");
3983 abort();
3984 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003985 }
3986 break;
3987 }
3988 }
3989
3990 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00003991 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003992
3993 if (RetTy != Type::VoidTy) {
3994 MVT::ValueType VT = getValueType(RetTy);
3995 switch (getTypeAction(VT)) {
3996 default: assert(0 && "Unknown type action!");
3997 case Legal:
3998 RetTys.push_back(VT);
3999 break;
4000 case Promote:
4001 RetTys.push_back(getTypeToTransformTo(VT));
4002 break;
4003 case Expand:
4004 if (VT != MVT::Vector) {
4005 // If this is a large integer, it needs to be reassembled from small
4006 // integers. Figure out what the source elt type is and how many small
4007 // integers it is.
Evan Cheng22cf8992006-12-13 20:57:08 +00004008 MVT::ValueType NVT = getTypeToExpandTo(VT);
4009 unsigned NumVals = getNumElements(VT);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004010 for (unsigned i = 0; i != NumVals; ++i)
4011 RetTys.push_back(NVT);
4012 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00004013 // Otherwise, this is a vector type. We only support legal vectors
4014 // right now.
Reid Spencerd84d35b2007-02-15 02:26:10 +00004015 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004016 unsigned NumElems = PTy->getNumElements();
4017 const Type *EltTy = PTy->getElementType();
4018
4019 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00004020 // type. If so, convert to the vector type.
Chris Lattnerb77ba732006-05-16 23:39:44 +00004021 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
4022 if (TVT != MVT::Other && isTypeLegal(TVT)) {
4023 RetTys.push_back(TVT);
4024 } else {
4025 assert(0 && "Don't support illegal by-val vector call results yet!");
4026 abort();
4027 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00004028 }
4029 }
4030 }
4031
4032 RetTys.push_back(MVT::Other); // Always has a chain.
4033
4034 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00004035 SDOperand Res = DAG.getNode(ISD::CALL,
4036 DAG.getVTList(&RetTys[0], RetTys.size()),
4037 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00004038
4039 // This returns a pair of operands. The first element is the
4040 // return value for the function (if RetTy is not VoidTy). The second
4041 // element is the outgoing token chain.
4042 SDOperand ResVal;
4043 if (RetTys.size() != 1) {
4044 MVT::ValueType VT = getValueType(RetTy);
4045 if (RetTys.size() == 2) {
4046 ResVal = Res;
4047
4048 // If this value was promoted, truncate it down.
4049 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00004050 if (VT == MVT::Vector) {
Chris Lattner77f04792007-03-25 05:00:54 +00004051 // Insert a VBIT_CONVERT to convert from the packed result type to the
Chris Lattnerb77ba732006-05-16 23:39:44 +00004052 // MVT::Vector type.
Reid Spencerd84d35b2007-02-15 02:26:10 +00004053 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
4054 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerb77ba732006-05-16 23:39:44 +00004055
4056 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencer09575ba2007-02-15 03:39:18 +00004057 // type. If so, convert to the vector type.
Chris Lattner296a83c2007-02-01 04:55:59 +00004058 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerb77ba732006-05-16 23:39:44 +00004059 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00004060 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
4061 // "N x PTyElementVT" MVT::Vector type.
4062 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00004063 DAG.getConstant(NumElems, MVT::i32),
4064 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00004065 } else {
4066 abort();
4067 }
4068 } else if (MVT::isInteger(VT)) {
Reid Spencere63b6512006-12-31 05:55:36 +00004069 unsigned AssertOp = ISD::AssertSext;
4070 if (!RetTyIsSigned)
4071 AssertOp = ISD::AssertZext;
Chris Lattneraaa23d92006-05-16 22:53:20 +00004072 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
4073 DAG.getValueType(VT));
4074 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
4075 } else {
4076 assert(MVT::isFloatingPoint(VT));
Evan Cheng4eee7242006-12-09 02:42:38 +00004077 if (getTypeAction(VT) == Expand)
4078 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
4079 else
4080 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattneraaa23d92006-05-16 22:53:20 +00004081 }
4082 }
4083 } else if (RetTys.size() == 3) {
4084 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
4085 Res.getValue(0), Res.getValue(1));
4086
4087 } else {
4088 assert(0 && "Case not handled yet!");
4089 }
4090 }
4091
4092 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
4093}
4094
Chris Lattner29dcc712005-05-14 05:50:48 +00004095SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00004096 assert(0 && "LowerOperation not implemented for this target!");
4097 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00004098 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00004099}
4100
Nate Begeman595ec732006-01-28 03:14:31 +00004101SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4102 SelectionDAG &DAG) {
4103 assert(0 && "CustomPromoteOperation not implemented for this target!");
4104 abort();
4105 return SDOperand();
4106}
4107
Evan Cheng6781b6e2006-02-15 21:59:04 +00004108/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00004109/// operand.
4110static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00004111 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004112 MVT::ValueType CurVT = VT;
4113 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4114 uint64_t Val = C->getValue() & 255;
4115 unsigned Shift = 8;
4116 while (CurVT != MVT::i8) {
4117 Val = (Val << Shift) | Val;
4118 Shift <<= 1;
4119 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004120 }
4121 return DAG.getConstant(Val, VT);
4122 } else {
4123 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
4124 unsigned Shift = 8;
4125 while (CurVT != MVT::i8) {
4126 Value =
4127 DAG.getNode(ISD::OR, VT,
4128 DAG.getNode(ISD::SHL, VT, Value,
4129 DAG.getConstant(Shift, MVT::i8)), Value);
4130 Shift <<= 1;
4131 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004132 }
4133
4134 return Value;
4135 }
4136}
4137
Evan Cheng6781b6e2006-02-15 21:59:04 +00004138/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4139/// used when a memcpy is turned into a memset when the source is a constant
4140/// string ptr.
4141static SDOperand getMemsetStringVal(MVT::ValueType VT,
4142 SelectionDAG &DAG, TargetLowering &TLI,
4143 std::string &Str, unsigned Offset) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00004144 uint64_t Val = 0;
4145 unsigned MSB = getSizeInBits(VT) / 8;
4146 if (TLI.isLittleEndian())
4147 Offset = Offset + MSB - 1;
4148 for (unsigned i = 0; i != MSB; ++i) {
Evan Cheng6e12a052006-11-29 01:38:07 +00004149 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng6781b6e2006-02-15 21:59:04 +00004150 Offset += TLI.isLittleEndian() ? -1 : 1;
4151 }
4152 return DAG.getConstant(Val, VT);
4153}
4154
Evan Cheng81fcea82006-02-14 08:22:34 +00004155/// getMemBasePlusOffset - Returns base and offset node for the
4156static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
4157 SelectionDAG &DAG, TargetLowering &TLI) {
4158 MVT::ValueType VT = Base.getValueType();
4159 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
4160}
4161
Evan Chengdb2a7a72006-02-14 20:12:38 +00004162/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00004163/// to replace the memset / memcpy is below the threshold. It also returns the
4164/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00004165static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
4166 unsigned Limit, uint64_t Size,
4167 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004168 MVT::ValueType VT;
4169
4170 if (TLI.allowsUnalignedMemoryAccesses()) {
4171 VT = MVT::i64;
4172 } else {
4173 switch (Align & 7) {
4174 case 0:
4175 VT = MVT::i64;
4176 break;
4177 case 4:
4178 VT = MVT::i32;
4179 break;
4180 case 2:
4181 VT = MVT::i16;
4182 break;
4183 default:
4184 VT = MVT::i8;
4185 break;
4186 }
4187 }
4188
Evan Chengd5026102006-02-14 09:11:59 +00004189 MVT::ValueType LVT = MVT::i64;
4190 while (!TLI.isTypeLegal(LVT))
4191 LVT = (MVT::ValueType)((unsigned)LVT - 1);
4192 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00004193
Evan Chengd5026102006-02-14 09:11:59 +00004194 if (VT > LVT)
4195 VT = LVT;
4196
Evan Cheng04514992006-02-14 23:05:54 +00004197 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00004198 while (Size != 0) {
4199 unsigned VTSize = getSizeInBits(VT) / 8;
4200 while (VTSize > Size) {
4201 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00004202 VTSize >>= 1;
4203 }
Evan Chengd5026102006-02-14 09:11:59 +00004204 assert(MVT::isInteger(VT));
4205
4206 if (++NumMemOps > Limit)
4207 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00004208 MemOps.push_back(VT);
4209 Size -= VTSize;
4210 }
Evan Chengd5026102006-02-14 09:11:59 +00004211
4212 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00004213}
4214
Chris Lattner875def92005-01-11 05:56:49 +00004215void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00004216 SDOperand Op1 = getValue(I.getOperand(1));
4217 SDOperand Op2 = getValue(I.getOperand(2));
4218 SDOperand Op3 = getValue(I.getOperand(3));
4219 SDOperand Op4 = getValue(I.getOperand(4));
4220 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
4221 if (Align == 0) Align = 1;
4222
4223 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
4224 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00004225
4226 // Expand memset / memcpy to a series of load / store ops
4227 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004228 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00004229 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00004230 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00004231 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00004232 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
4233 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00004234 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00004235 unsigned Offset = 0;
4236 for (unsigned i = 0; i < NumMemOps; i++) {
4237 MVT::ValueType VT = MemOps[i];
4238 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00004239 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00004240 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00004241 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004242 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00004243 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00004244 Offset += VTSize;
4245 }
Evan Cheng81fcea82006-02-14 08:22:34 +00004246 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004247 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00004248 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004249 case ISD::MEMCPY: {
4250 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
4251 Size->getValue(), Align, TLI)) {
4252 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004253 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004254 GlobalAddressSDNode *G = NULL;
4255 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004256 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004257
4258 if (Op2.getOpcode() == ISD::GlobalAddress)
4259 G = cast<GlobalAddressSDNode>(Op2);
4260 else if (Op2.getOpcode() == ISD::ADD &&
4261 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4262 Op2.getOperand(1).getOpcode() == ISD::Constant) {
4263 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004264 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00004265 }
4266 if (G) {
4267 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengfeba5072006-11-29 01:58:12 +00004268 if (GV && GV->isConstant()) {
Evan Cheng38280c02006-03-10 23:52:03 +00004269 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004270 if (!Str.empty()) {
4271 CopyFromStr = true;
4272 SrcOff += SrcDelta;
4273 }
4274 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00004275 }
4276
Evan Chenge2038bd2006-02-15 01:54:51 +00004277 for (unsigned i = 0; i < NumMemOps; i++) {
4278 MVT::ValueType VT = MemOps[i];
4279 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00004280 SDOperand Value, Chain, Store;
4281
Evan Chengc3dcf5a2006-02-16 23:11:42 +00004282 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00004283 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
4284 Chain = getRoot();
4285 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00004286 DAG.getStore(Chain, Value,
4287 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004288 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004289 } else {
4290 Value = DAG.getLoad(VT, getRoot(),
4291 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00004292 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004293 Chain = Value.getValue(1);
4294 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00004295 DAG.getStore(Chain, Value,
4296 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00004297 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004298 }
Evan Chenge2038bd2006-02-15 01:54:51 +00004299 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00004300 SrcOff += VTSize;
4301 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00004302 }
4303 }
4304 break;
4305 }
4306 }
4307
4308 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004309 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4310 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00004311 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00004312 }
4313 }
4314
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004315 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00004316}
4317
Chris Lattner875def92005-01-11 05:56:49 +00004318//===----------------------------------------------------------------------===//
4319// SelectionDAGISel code
4320//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00004321
4322unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
4323 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
4324}
4325
Chris Lattnerc9950c12005-08-17 06:37:43 +00004326void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004327 AU.addRequired<AliasAnalysis>();
Chris Lattnerf6a6d3c2007-03-31 04:18:03 +00004328 AU.setPreservesAll();
Chris Lattnerc9950c12005-08-17 06:37:43 +00004329}
Chris Lattner7a60d912005-01-07 07:47:53 +00004330
Chris Lattner35397782005-12-05 07:10:48 +00004331
Chris Lattnerbba52192006-10-28 19:22:10 +00004332
Chris Lattner7a60d912005-01-07 07:47:53 +00004333bool SelectionDAGISel::runOnFunction(Function &Fn) {
4334 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4335 RegMap = MF.getSSARegMap();
Bill Wendling22e978a2006-12-07 20:04:42 +00004336 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004337
4338 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4339
4340 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4341 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00004342
Evan Cheng276b44b2007-02-10 02:43:39 +00004343 // Add function live-ins to entry block live-in set.
4344 BasicBlock *EntryBB = &Fn.getEntryBlock();
4345 BB = FuncInfo.MBBMap[EntryBB];
4346 if (!MF.livein_empty())
4347 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4348 E = MF.livein_end(); I != E; ++I)
4349 BB->addLiveIn(I->first);
4350
Chris Lattner7a60d912005-01-07 07:47:53 +00004351 return true;
4352}
4353
Chris Lattnered0110b2006-10-27 21:36:01 +00004354SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4355 unsigned Reg) {
4356 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00004357 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00004358 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00004359 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00004360
4361 // If this type is not legal, we must make sure to not create an invalid
4362 // register use.
4363 MVT::ValueType SrcVT = Op.getValueType();
4364 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00004365 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00004366 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00004367 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00004368 // Handle copies from generic vectors to registers.
4369 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencerd84d35b2007-02-15 02:26:10 +00004370 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner5fe1f542006-03-31 02:06:56 +00004371 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00004372
Chris Lattner5fe1f542006-03-31 02:06:56 +00004373 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4374 // MVT::Vector type.
4375 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4376 DAG.getConstant(NE, MVT::i32),
4377 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00004378
Chris Lattner5fe1f542006-03-31 02:06:56 +00004379 // Loop over all of the elements of the resultant vector,
4380 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4381 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004382 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00004383 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00004384 for (unsigned i = 0; i != NE; ++i) {
4385 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004386 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004387 if (PTyElementVT == PTyLegalElementVT) {
4388 // Elements are legal.
4389 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4390 } else if (PTyLegalElementVT > PTyElementVT) {
4391 // Elements are promoted.
4392 if (MVT::isFloatingPoint(PTyLegalElementVT))
4393 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4394 else
4395 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4396 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4397 } else {
4398 // Elements are expanded.
4399 // The src value is expanded into multiple registers.
4400 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004401 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004402 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004403 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00004404 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4405 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4406 }
Chris Lattner672a42d2006-03-21 19:20:37 +00004407 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004408 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4409 &OutChains[0], OutChains.size());
Evan Cheng22cf8992006-12-13 20:57:08 +00004410 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattner33182322005-08-16 21:55:35 +00004411 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00004412 if (MVT::isFloatingPoint(SrcVT))
4413 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4414 else
Chris Lattnera66403d2005-09-02 00:19:37 +00004415 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00004416 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00004417 } else {
Evan Cheng22cf8992006-12-13 20:57:08 +00004418 DestVT = TLI.getTypeToExpandTo(SrcVT);
4419 unsigned NumVals = TLI.getNumElements(SrcVT);
4420 if (NumVals == 1)
4421 return DAG.getCopyToReg(getRoot(), Reg,
4422 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4423 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattner33182322005-08-16 21:55:35 +00004424 // The src value is expanded into multiple registers.
4425 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004426 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00004427 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00004428 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00004429 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00004430 return DAG.getCopyToReg(Op, Reg+1, Hi);
4431 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004432}
4433
Chris Lattner16f64df2005-01-17 17:15:02 +00004434void SelectionDAGISel::
Evan Chengde608342007-02-10 01:08:18 +00004435LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner16f64df2005-01-17 17:15:02 +00004436 std::vector<SDOperand> &UnorderedChains) {
4437 // If this is the entry block, emit arguments.
Evan Chengde608342007-02-10 01:08:18 +00004438 Function &F = *LLVMBB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004439 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00004440 SDOperand OldRoot = SDL.DAG.getRoot();
4441 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00004442
Chris Lattner6871b232005-10-30 19:42:35 +00004443 unsigned a = 0;
4444 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4445 AI != E; ++AI, ++a)
4446 if (!AI->use_empty()) {
4447 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00004448
Chris Lattner6871b232005-10-30 19:42:35 +00004449 // If this argument is live outside of the entry block, insert a copy from
4450 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner8c504cf2007-02-25 18:40:32 +00004451 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4452 if (VMI != FuncInfo.ValueMap.end()) {
4453 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattner6871b232005-10-30 19:42:35 +00004454 UnorderedChains.push_back(Copy);
4455 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00004456 }
Chris Lattner6871b232005-10-30 19:42:35 +00004457
Chris Lattner6871b232005-10-30 19:42:35 +00004458 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00004459 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00004460 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00004461}
4462
Chris Lattner7a60d912005-01-07 07:47:53 +00004463void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4464 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00004465 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00004466 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00004467
4468 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00004469
Chris Lattner6871b232005-10-30 19:42:35 +00004470 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00004471 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Chris Lattner6871b232005-10-30 19:42:35 +00004472 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00004473
4474 BB = FuncInfo.MBBMap[LLVMBB];
4475 SDL.setCurrentBasicBlock(BB);
4476
4477 // Lower all of the non-terminator instructions.
4478 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4479 I != E; ++I)
4480 SDL.visit(*I);
Jim Laskey14059d92007-02-25 21:43:59 +00004481
4482 // Lower call part of invoke.
4483 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
4484 if (Invoke) SDL.visitInvoke(*Invoke, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004485
Chris Lattner7a60d912005-01-07 07:47:53 +00004486 // Ensure that all instructions which are used outside of their defining
4487 // blocks are available as virtual registers.
4488 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00004489 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner289aa442007-02-04 01:35:11 +00004490 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00004491 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00004492 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00004493 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00004494 }
4495
4496 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4497 // ensure constants are generated when needed. Remember the virtual registers
4498 // that need to be added to the Machine PHI nodes as input. We cannot just
4499 // directly add them, because expansion might result in multiple MBB's for one
4500 // BB. As such, the start of the BB might correspond to a different MBB than
4501 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00004502 //
Chris Lattner84a03502006-10-27 23:50:33 +00004503 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00004504
4505 // Emit constants only once even if used by multiple PHI nodes.
4506 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00004507
Chris Lattner84a03502006-10-27 23:50:33 +00004508 // Vector bool would be better, but vector<bool> is really slow.
4509 std::vector<unsigned char> SuccsHandled;
4510 if (TI->getNumSuccessors())
4511 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4512
Chris Lattner7a60d912005-01-07 07:47:53 +00004513 // Check successor nodes PHI nodes that expect a constant to be available from
4514 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00004515 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4516 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00004517 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00004518 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00004519
Chris Lattner84a03502006-10-27 23:50:33 +00004520 // If this terminator has multiple identical successors (common for
4521 // switches), only handle each succ once.
4522 unsigned SuccMBBNo = SuccMBB->getNumber();
4523 if (SuccsHandled[SuccMBBNo]) continue;
4524 SuccsHandled[SuccMBBNo] = true;
4525
4526 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00004527 PHINode *PN;
4528
4529 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4530 // nodes and Machine PHI nodes, but the incoming operands have not been
4531 // emitted yet.
4532 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00004533 (PN = dyn_cast<PHINode>(I)); ++I) {
4534 // Ignore dead phi's.
4535 if (PN->use_empty()) continue;
4536
4537 unsigned Reg;
4538 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner90f42382006-11-29 01:12:32 +00004539
Chris Lattner84a03502006-10-27 23:50:33 +00004540 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4541 unsigned &RegOut = ConstantsOut[C];
4542 if (RegOut == 0) {
4543 RegOut = FuncInfo.CreateRegForValue(C);
4544 UnorderedChains.push_back(
4545 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00004546 }
Chris Lattner84a03502006-10-27 23:50:33 +00004547 Reg = RegOut;
4548 } else {
4549 Reg = FuncInfo.ValueMap[PHIOp];
4550 if (Reg == 0) {
4551 assert(isa<AllocaInst>(PHIOp) &&
4552 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4553 "Didn't codegen value into a register!??");
4554 Reg = FuncInfo.CreateRegForValue(PHIOp);
4555 UnorderedChains.push_back(
4556 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00004557 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004558 }
Chris Lattner84a03502006-10-27 23:50:33 +00004559
4560 // Remember that this register needs to added to the machine PHI node as
4561 // the input for this MBB.
4562 MVT::ValueType VT = TLI.getValueType(PN->getType());
4563 unsigned NumElements;
4564 if (VT != MVT::Vector)
4565 NumElements = TLI.getNumElements(VT);
4566 else {
4567 MVT::ValueType VT1,VT2;
4568 NumElements =
Reid Spencerd84d35b2007-02-15 02:26:10 +00004569 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner84a03502006-10-27 23:50:33 +00004570 VT1, VT2);
4571 }
4572 for (unsigned i = 0, e = NumElements; i != e; ++i)
4573 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4574 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004575 }
4576 ConstantsOut.clear();
4577
Chris Lattner718b5c22005-01-13 17:59:43 +00004578 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00004579 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00004580 SDOperand Root = SDL.getRoot();
4581 if (Root.getOpcode() != ISD::EntryToken) {
4582 unsigned i = 0, e = UnorderedChains.size();
4583 for (; i != e; ++i) {
4584 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4585 if (UnorderedChains[i].Val->getOperand(0) == Root)
4586 break; // Don't add the root if we already indirectly depend on it.
4587 }
4588
4589 if (i == e)
4590 UnorderedChains.push_back(Root);
4591 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004592 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4593 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00004594 }
4595
Chris Lattner7a60d912005-01-07 07:47:53 +00004596 // Lower the terminator after the copies are emitted.
Jim Laskey14059d92007-02-25 21:43:59 +00004597 if (Invoke) {
4598 // Just the branch part of invoke.
4599 SDL.visitInvoke(*Invoke, true);
4600 } else {
4601 SDL.visit(*LLVMBB->getTerminator());
4602 }
Chris Lattner4108bb02005-01-17 19:43:36 +00004603
Nate Begemaned728c12006-03-27 01:32:24 +00004604 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004605 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00004606 SwitchCases.clear();
4607 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov70378262007-03-25 15:07:15 +00004608 JTCases.clear();
4609 JTCases = SDL.JTCases;
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004610 BitTestCases.clear();
4611 BitTestCases = SDL.BitTestCases;
4612
Chris Lattner4108bb02005-01-17 19:43:36 +00004613 // Make sure the root of the DAG is up-to-date.
4614 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00004615}
4616
Nate Begemaned728c12006-03-27 01:32:24 +00004617void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004618 // Get alias analysis for load/store combining.
4619 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4620
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004621 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004622 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004623
Bill Wendling22e978a2006-12-07 20:04:42 +00004624 DOUT << "Lowered selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004625 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004626
Chris Lattner7a60d912005-01-07 07:47:53 +00004627 // Second step, hack on the DAG until it only uses operations and types that
4628 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004629 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004630
Bill Wendling22e978a2006-12-07 20:04:42 +00004631 DOUT << "Legalized selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004632 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004633
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004634 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004635 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004636
Evan Cheng739a6a42006-01-21 02:32:06 +00004637 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004638
Chris Lattner5ca31d92005-03-30 01:10:47 +00004639 // Third, instruction select all of the operations to machine code, adding the
4640 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004641 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004642
Bill Wendling22e978a2006-12-07 20:04:42 +00004643 DOUT << "Selected machine code:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004644 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004645}
Chris Lattner7a60d912005-01-07 07:47:53 +00004646
Nate Begemaned728c12006-03-27 01:32:24 +00004647void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4648 FunctionLoweringInfo &FuncInfo) {
4649 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4650 {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004651 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004652 CurDAG = &DAG;
4653
4654 // First step, lower LLVM code to some DAG. This DAG may use operations and
4655 // types that are not supported by the target.
4656 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4657
4658 // Second step, emit the lowered DAG as machine code.
4659 CodeGenAndEmitDAG(DAG);
4660 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004661
4662 DOUT << "Total amount of phi nodes to update: "
4663 << PHINodesToUpdate.size() << "\n";
4664 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4665 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4666 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemaned728c12006-03-27 01:32:24 +00004667
Chris Lattner5ca31d92005-03-30 01:10:47 +00004668 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004669 // PHI nodes in successors.
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004670 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemaned728c12006-03-27 01:32:24 +00004671 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4672 MachineInstr *PHI = PHINodesToUpdate[i].first;
4673 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4674 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004675 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004676 PHI->addMachineBasicBlockOperand(BB);
4677 }
4678 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004679 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004680
4681 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4682 // Lower header first, if it wasn't already lowered
4683 if (!BitTestCases[i].Emitted) {
4684 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4685 CurDAG = &HSDAG;
4686 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4687 // Set the current basic block to the mbb we wish to insert the code into
4688 BB = BitTestCases[i].Parent;
4689 HSDL.setCurrentBasicBlock(BB);
4690 // Emit the code
4691 HSDL.visitBitTestHeader(BitTestCases[i]);
4692 HSDAG.setRoot(HSDL.getRoot());
4693 CodeGenAndEmitDAG(HSDAG);
4694 }
4695
4696 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4697 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4698 CurDAG = &BSDAG;
4699 SelectionDAGLowering BSDL(BSDAG, TLI, FuncInfo);
4700 // Set the current basic block to the mbb we wish to insert the code into
4701 BB = BitTestCases[i].Cases[j].ThisBB;
4702 BSDL.setCurrentBasicBlock(BB);
4703 // Emit the code
4704 if (j+1 != ej)
4705 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4706 BitTestCases[i].Reg,
4707 BitTestCases[i].Cases[j]);
4708 else
4709 BSDL.visitBitTestCase(BitTestCases[i].Default,
4710 BitTestCases[i].Reg,
4711 BitTestCases[i].Cases[j]);
4712
4713
4714 BSDAG.setRoot(BSDL.getRoot());
4715 CodeGenAndEmitDAG(BSDAG);
4716 }
4717
4718 // Update PHI Nodes
4719 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4720 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4721 MachineBasicBlock *PHIBB = PHI->getParent();
4722 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4723 "This is not a machine PHI node that we are updating!");
4724 // This is "default" BB. We have two jumps to it. From "header" BB and
4725 // from last "case" BB.
4726 if (PHIBB == BitTestCases[i].Default) {
4727 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4728 PHI->addMachineBasicBlockOperand(BitTestCases[i].Parent);
Anton Korobeynikove2880402007-04-13 06:53:51 +00004729 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004730 PHI->addMachineBasicBlockOperand(BitTestCases[i].Cases.back().ThisBB);
4731 }
4732 // One of "cases" BB.
4733 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4734 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4735 if (cBB->succ_end() !=
4736 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
4737 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4738 PHI->addMachineBasicBlockOperand(cBB);
4739 }
4740 }
4741 }
4742 }
4743
Nate Begeman866b4b42006-04-23 06:26:20 +00004744 // If the JumpTable record is filled in, then we need to emit a jump table.
4745 // Updating the PHI nodes is tricky in this case, since we need to determine
4746 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov70378262007-03-25 15:07:15 +00004747 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4748 // Lower header first, if it wasn't already lowered
4749 if (!JTCases[i].first.Emitted) {
4750 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4751 CurDAG = &HSDAG;
4752 SelectionDAGLowering HSDL(HSDAG, TLI, FuncInfo);
4753 // Set the current basic block to the mbb we wish to insert the code into
4754 BB = JTCases[i].first.HeaderBB;
4755 HSDL.setCurrentBasicBlock(BB);
4756 // Emit the code
4757 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4758 HSDAG.setRoot(HSDL.getRoot());
4759 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004760 }
Anton Korobeynikov70378262007-03-25 15:07:15 +00004761
4762 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4763 CurDAG = &JSDAG;
4764 SelectionDAGLowering JSDL(JSDAG, TLI, FuncInfo);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004765 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov70378262007-03-25 15:07:15 +00004766 BB = JTCases[i].second.MBB;
4767 JSDL.setCurrentBasicBlock(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004768 // Emit the code
Anton Korobeynikov70378262007-03-25 15:07:15 +00004769 JSDL.visitJumpTable(JTCases[i].second);
4770 JSDAG.setRoot(JSDL.getRoot());
4771 CodeGenAndEmitDAG(JSDAG);
4772
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004773 // Update PHI Nodes
4774 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4775 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4776 MachineBasicBlock *PHIBB = PHI->getParent();
4777 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4778 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004779 // "default" BB. We can go there only from header BB.
Anton Korobeynikov70378262007-03-25 15:07:15 +00004780 if (PHIBB == JTCases[i].second.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004781 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Anton Korobeynikov70378262007-03-25 15:07:15 +00004782 PHI->addMachineBasicBlockOperand(JTCases[i].first.HeaderBB);
Nate Begemandf488392006-05-03 03:48:02 +00004783 }
Anton Korobeynikov506eaf72007-04-09 12:31:58 +00004784 // JT BB. Just iterate over successors here
Nate Begemandf488392006-05-03 03:48:02 +00004785 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004786 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004787 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004788 }
4789 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004790 }
4791
Chris Lattner76a7bc82006-10-22 23:00:53 +00004792 // If the switch block involved a branch to one of the actual successors, we
4793 // need to update PHI nodes in that block.
4794 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4795 MachineInstr *PHI = PHINodesToUpdate[i].first;
4796 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4797 "This is not a machine PHI node that we are updating!");
4798 if (BB->isSuccessor(PHI->getParent())) {
4799 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4800 PHI->addMachineBasicBlockOperand(BB);
4801 }
4802 }
4803
Nate Begemaned728c12006-03-27 01:32:24 +00004804 // If we generated any switch lowering information, build and codegen any
4805 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004806 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskeyc56315c2007-01-26 21:22:28 +00004807 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemaned728c12006-03-27 01:32:24 +00004808 CurDAG = &SDAG;
4809 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004810
Nate Begemaned728c12006-03-27 01:32:24 +00004811 // Set the current basic block to the mbb we wish to insert the code into
4812 BB = SwitchCases[i].ThisBB;
4813 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004814
Nate Begemaned728c12006-03-27 01:32:24 +00004815 // Emit the code
4816 SDL.visitSwitchCase(SwitchCases[i]);
4817 SDAG.setRoot(SDL.getRoot());
4818 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004819
4820 // Handle any PHI nodes in successors of this chunk, as if we were coming
4821 // from the original BB before switch expansion. Note that PHI nodes can
4822 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4823 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004824 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004825 for (MachineBasicBlock::iterator Phi = BB->begin();
4826 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4827 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4828 for (unsigned pn = 0; ; ++pn) {
4829 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4830 if (PHINodesToUpdate[pn].first == Phi) {
4831 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4832 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4833 break;
4834 }
4835 }
Nate Begemaned728c12006-03-27 01:32:24 +00004836 }
Chris Lattner707339a52006-09-07 01:59:34 +00004837
4838 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004839 if (BB == SwitchCases[i].FalseBB)
4840 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004841
4842 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004843 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004844 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004845 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004846 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004847 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004848}
Evan Cheng739a6a42006-01-21 02:32:06 +00004849
Jim Laskey95eda5b2006-08-01 14:21:23 +00004850
Evan Cheng739a6a42006-01-21 02:32:06 +00004851//===----------------------------------------------------------------------===//
4852/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4853/// target node in the graph.
4854void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4855 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004856
Jim Laskey29e635d2006-08-02 12:30:23 +00004857 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004858
4859 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004860 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004861 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004862 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004863
Jim Laskey03593f72006-08-01 18:29:48 +00004864 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004865 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004866 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004867}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004868
Chris Lattner47639db2006-03-06 00:22:00 +00004869
Jim Laskey03593f72006-08-01 18:29:48 +00004870HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4871 return new HazardRecognizer();
4872}
4873
Chris Lattner6df34962006-10-11 03:58:02 +00004874//===----------------------------------------------------------------------===//
4875// Helper functions used by the generated instruction selector.
4876//===----------------------------------------------------------------------===//
4877// Calls to these methods are generated by tblgen.
4878
4879/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4880/// the dag combiner simplified the 255, we still want to match. RHS is the
4881/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4882/// specified in the .td file (e.g. 255).
4883bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4884 int64_t DesiredMaskS) {
4885 uint64_t ActualMask = RHS->getValue();
4886 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4887
4888 // If the actual mask exactly matches, success!
4889 if (ActualMask == DesiredMask)
4890 return true;
4891
4892 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4893 if (ActualMask & ~DesiredMask)
4894 return false;
4895
4896 // Otherwise, the DAG Combiner may have proven that the value coming in is
4897 // either already zero or is not demanded. Check for known zero input bits.
4898 uint64_t NeededMask = DesiredMask & ~ActualMask;
4899 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4900 return true;
4901
4902 // TODO: check to see if missing bits are just not demanded.
4903
4904 // Otherwise, this pattern doesn't match.
4905 return false;
4906}
4907
4908/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4909/// the dag combiner simplified the 255, we still want to match. RHS is the
4910/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4911/// specified in the .td file (e.g. 255).
4912bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4913 int64_t DesiredMaskS) {
4914 uint64_t ActualMask = RHS->getValue();
4915 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4916
4917 // If the actual mask exactly matches, success!
4918 if (ActualMask == DesiredMask)
4919 return true;
4920
4921 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4922 if (ActualMask & ~DesiredMask)
4923 return false;
4924
4925 // Otherwise, the DAG Combiner may have proven that the value coming in is
4926 // either already zero or is not demanded. Check for known zero input bits.
4927 uint64_t NeededMask = DesiredMask & ~ActualMask;
4928
4929 uint64_t KnownZero, KnownOne;
4930 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4931
4932 // If all the missing bits in the or are already known to be set, match!
4933 if ((NeededMask & KnownOne) == NeededMask)
4934 return true;
4935
4936 // TODO: check to see if missing bits are just not demanded.
4937
4938 // Otherwise, this pattern doesn't match.
4939 return false;
4940}
4941
Jim Laskey03593f72006-08-01 18:29:48 +00004942
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004943/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4944/// by tblgen. Others should not call it.
4945void SelectionDAGISel::
4946SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4947 std::vector<SDOperand> InOps;
4948 std::swap(InOps, Ops);
4949
4950 Ops.push_back(InOps[0]); // input chain.
4951 Ops.push_back(InOps[1]); // input asm string.
4952
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004953 unsigned i = 2, e = InOps.size();
4954 if (InOps[e-1].getValueType() == MVT::Flag)
4955 --e; // Don't process a flag operand if it is here.
4956
4957 while (i != e) {
4958 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4959 if ((Flags & 7) != 4 /*MEM*/) {
4960 // Just skip over this operand, copying the operands verbatim.
4961 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4962 i += (Flags >> 3) + 1;
4963 } else {
4964 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4965 // Otherwise, this is a memory operand. Ask the target to select it.
4966 std::vector<SDOperand> SelOps;
4967 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling22e978a2006-12-07 20:04:42 +00004968 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004969 exit(1);
4970 }
4971
4972 // Add this to the output node.
Chris Lattnerb49917d2007-04-09 00:33:58 +00004973 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner9bd5ed62006-12-16 21:14:48 +00004974 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattnerb49917d2007-04-09 00:33:58 +00004975 IntPtrTy));
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004976 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4977 i += 2;
4978 }
4979 }
4980
4981 // Add the flag input back if present.
4982 if (e != InOps.size())
4983 Ops.push_back(InOps.back());
4984}