blob: e8d58453c240d8931b698541c7ce43b6919fc2f9 [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"
Jim Laskeydcb2b832006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000016#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000017#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000018#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000022#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Jim Laskey219d5592006-01-04 22:28:25 +000027#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000030#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000031#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000032#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/CodeGen/SelectionDAG.h"
34#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000035#include "llvm/Target/MRegisterInfo.h"
Chris Lattner90f42382006-11-29 01:12:32 +000036#include "llvm/Target/TargetAsmInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetFrameInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.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///
64/// RegisterScheduler class - Track the registration of instruction schedulers.
65///
66//===---------------------------------------------------------------------===//
67MachinePassRegistry RegisterScheduler::Registry;
68
69//===---------------------------------------------------------------------===//
70///
71/// ISHeuristic command line option for instruction schedulers.
72///
73//===---------------------------------------------------------------------===//
Evan Chengc1e1d972006-01-23 07:01:07 +000074namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000075 cl::opt<RegisterScheduler::FunctionPassCtor, false,
76 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000077 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000078 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000079 cl::desc("Instruction schedulers available:"));
80
Jim Laskey03593f72006-08-01 18:29:48 +000081 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000082 defaultListDAGScheduler("default", " Best scheduler for the target",
83 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000084} // namespace
85
Chris Lattner6f87d182006-02-22 22:37:12 +000086namespace {
87 /// RegsForValue - This struct represents the physical registers that a
88 /// particular value is assigned and the type information about the value.
89 /// This is needed because values can be promoted into larger registers and
90 /// expanded into multiple smaller registers than the value.
Chris Lattner996795b2006-06-28 23:17:24 +000091 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-02-22 22:37:12 +000092 /// Regs - This list hold the register (for legal and promoted values)
93 /// or register set (for expanded values) that the value should be assigned
94 /// to.
95 std::vector<unsigned> Regs;
96
97 /// RegVT - The value type of each register.
98 ///
99 MVT::ValueType RegVT;
100
101 /// ValueVT - The value type of the LLVM value, which may be promoted from
102 /// RegVT or made from merging the two expanded parts.
103 MVT::ValueType ValueVT;
104
105 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
106
107 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
108 : RegVT(regvt), ValueVT(valuevt) {
109 Regs.push_back(Reg);
110 }
111 RegsForValue(const std::vector<unsigned> &regs,
112 MVT::ValueType regvt, MVT::ValueType valuevt)
113 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
114 }
115
116 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
117 /// this value and returns the result as a ValueVT value. This uses
118 /// Chain/Flag as the input and updates them for the output Chain/Flag.
119 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000120 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000121
122 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
123 /// specified value into the registers specified by this object. This uses
124 /// Chain/Flag as the input and updates them for the output Chain/Flag.
125 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +0000126 SDOperand &Chain, SDOperand &Flag,
127 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000128
129 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130 /// operand list. This adds the code marker and includes the number of
131 /// values added into it.
132 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000133 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000134 };
135}
Evan Chengc1e1d972006-01-23 07:01:07 +0000136
Chris Lattner7a60d912005-01-07 07:47:53 +0000137namespace llvm {
138 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-08-01 19:14:14 +0000139 /// createDefaultScheduler - This creates an instruction scheduler appropriate
140 /// for the target.
141 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
142 SelectionDAG *DAG,
143 MachineBasicBlock *BB) {
144 TargetLowering &TLI = IS->getTargetLowering();
145
146 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
147 return createTDListDAGScheduler(IS, DAG, BB);
148 } else {
149 assert(TLI.getSchedulingPreference() ==
150 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
151 return createBURRListDAGScheduler(IS, DAG, BB);
152 }
153 }
154
155
156 //===--------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +0000157 /// FunctionLoweringInfo - This contains information that is global to a
158 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000159 class FunctionLoweringInfo {
160 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000161 TargetLowering &TLI;
162 Function &Fn;
163 MachineFunction &MF;
164 SSARegMap *RegMap;
165
166 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
167
168 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
169 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
170
171 /// ValueMap - Since we emit code for the function a basic block at a time,
172 /// we must remember which virtual registers hold the values for
173 /// cross-basic-block values.
174 std::map<const Value*, unsigned> ValueMap;
175
176 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
177 /// the entry block. This allows the allocas to be efficiently referenced
178 /// anywhere in the function.
179 std::map<const AllocaInst*, int> StaticAllocaMap;
180
181 unsigned MakeReg(MVT::ValueType VT) {
182 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
183 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000184
185 /// isExportedInst - Return true if the specified value is an instruction
186 /// exported from its block.
187 bool isExportedInst(const Value *V) {
188 return ValueMap.count(V);
189 }
Misha Brukman835702a2005-04-21 22:36:52 +0000190
Chris Lattner49409cb2006-03-16 19:51:18 +0000191 unsigned CreateRegForValue(const Value *V);
192
Chris Lattner7a60d912005-01-07 07:47:53 +0000193 unsigned InitializeRegForValue(const Value *V) {
194 unsigned &R = ValueMap[V];
195 assert(R == 0 && "Already initialized this value register!");
196 return R = CreateRegForValue(V);
197 }
198 };
199}
200
201/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemaned728c12006-03-27 01:32:24 +0000202/// PHI nodes or outside of the basic block that defines it, or used by a
203/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner7a60d912005-01-07 07:47:53 +0000204static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
205 if (isa<PHINode>(I)) return true;
206 BasicBlock *BB = I->getParent();
207 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000208 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattnered0110b2006-10-27 21:36:01 +0000209 // FIXME: Remove switchinst special case.
Nate Begemaned728c12006-03-27 01:32:24 +0000210 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000211 return true;
212 return false;
213}
214
Chris Lattner6871b232005-10-30 19:42:35 +0000215/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-03-27 01:32:24 +0000216/// entry block, return true. This includes arguments used by switches, since
217/// the switch may expand into multiple basic blocks.
Chris Lattner6871b232005-10-30 19:42:35 +0000218static bool isOnlyUsedInEntryBlock(Argument *A) {
219 BasicBlock *Entry = A->getParent()->begin();
220 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemaned728c12006-03-27 01:32:24 +0000221 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000222 return false; // Use not in entry block.
223 return true;
224}
225
Chris Lattner7a60d912005-01-07 07:47:53 +0000226FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000227 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000228 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
229
Chris Lattner6871b232005-10-30 19:42:35 +0000230 // Create a vreg for each argument register that is not dead and is used
231 // outside of the entry block for the function.
232 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
233 AI != E; ++AI)
234 if (!isOnlyUsedInEntryBlock(AI))
235 InitializeRegForValue(AI);
236
Chris Lattner7a60d912005-01-07 07:47:53 +0000237 // Initialize the mapping of values to registers. This is only set up for
238 // instruction values that are used outside of the block that defines
239 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000240 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
242 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000243 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000244 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000245 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000246 unsigned Align =
Chris Lattner50ee0e42007-01-20 22:35:55 +0000247 std::max((unsigned)TLI.getTargetData()->getTypeAlignmentPref(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000248 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000249
Reid Spencere0fc4df2006-10-20 07:07:24 +0000250 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000251 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000252 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000253 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000254 }
255
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000256 for (; BB != EB; ++BB)
257 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000258 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
259 if (!isa<AllocaInst>(I) ||
260 !StaticAllocaMap.count(cast<AllocaInst>(I)))
261 InitializeRegForValue(I);
262
263 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
264 // also creates the initial PHI MachineInstrs, though none of the input
265 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000266 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000267 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
268 MBBMap[BB] = MBB;
269 MF.getBasicBlockList().push_back(MBB);
270
271 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
272 // appropriate.
273 PHINode *PN;
Chris Lattner84a03502006-10-27 23:50:33 +0000274 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
275 if (PN->use_empty()) continue;
276
277 MVT::ValueType VT = TLI.getValueType(PN->getType());
278 unsigned NumElements;
279 if (VT != MVT::Vector)
280 NumElements = TLI.getNumElements(VT);
281 else {
282 MVT::ValueType VT1,VT2;
283 NumElements =
284 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
285 VT1, VT2);
Chris Lattner8ea875f2005-01-07 21:34:19 +0000286 }
Chris Lattner84a03502006-10-27 23:50:33 +0000287 unsigned PHIReg = ValueMap[PN];
288 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Cheng20350c42006-11-27 23:37:22 +0000289 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner84a03502006-10-27 23:50:33 +0000290 for (unsigned i = 0; i != NumElements; ++i)
Evan Cheng20350c42006-11-27 23:37:22 +0000291 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner84a03502006-10-27 23:50:33 +0000292 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000293 }
294}
295
Chris Lattner49409cb2006-03-16 19:51:18 +0000296/// CreateRegForValue - Allocate the appropriate number of virtual registers of
297/// the correctly promoted or expanded types. Assign these registers
298/// consecutive vreg numbers and return the first assigned number.
299unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
300 MVT::ValueType VT = TLI.getValueType(V->getType());
301
302 // The number of multiples of registers that we need, to, e.g., split up
303 // a <2 x int64> -> 4 x i32 registers.
304 unsigned NumVectorRegs = 1;
305
306 // If this is a packed type, figure out what type it will decompose into
307 // and how many of the elements it will use.
308 if (VT == MVT::Vector) {
309 const PackedType *PTy = cast<PackedType>(V->getType());
310 unsigned NumElts = PTy->getNumElements();
311 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
312
313 // Divide the input until we get to a supported size. This will always
314 // end with a scalar if the target doesn't support vectors.
315 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
316 NumElts >>= 1;
317 NumVectorRegs <<= 1;
318 }
Chris Lattner7ececaa2006-03-16 23:05:19 +0000319 if (NumElts == 1)
320 VT = EltTy;
321 else
322 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-03-16 19:51:18 +0000323 }
324
325 // The common case is that we will only create one register for this
326 // value. If we have that case, create and return the virtual register.
327 unsigned NV = TLI.getNumElements(VT);
328 if (NV == 1) {
329 // If we are promoting this value, pick the next largest supported type.
330 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
331 unsigned Reg = MakeReg(PromotedType);
332 // If this is a vector of supported or promoted types (e.g. 4 x i16),
333 // create all of the registers.
334 for (unsigned i = 1; i != NumVectorRegs; ++i)
335 MakeReg(PromotedType);
336 return Reg;
337 }
338
339 // If this value is represented with multiple target registers, make sure
340 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng22cf8992006-12-13 20:57:08 +0000341 VT = TLI.getTypeToExpandTo(VT);
342 unsigned R = MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000343 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng22cf8992006-12-13 20:57:08 +0000344 MakeReg(VT);
Chris Lattner49409cb2006-03-16 19:51:18 +0000345 return R;
346}
Chris Lattner7a60d912005-01-07 07:47:53 +0000347
348//===----------------------------------------------------------------------===//
349/// SelectionDAGLowering - This is the common target-independent lowering
350/// implementation that is parameterized by a TargetLowering object.
351/// Also, targets can overload any lowering method.
352///
353namespace llvm {
354class SelectionDAGLowering {
355 MachineBasicBlock *CurMBB;
356
357 std::map<const Value*, SDOperand> NodeMap;
358
Chris Lattner4d9651c2005-01-17 22:19:26 +0000359 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
360 /// them up and then emit token factor nodes when possible. This allows us to
361 /// get simple disambiguation between loads without worrying about alias
362 /// analysis.
363 std::vector<SDOperand> PendingLoads;
364
Nate Begemaned728c12006-03-27 01:32:24 +0000365 /// Case - A pair of values to record the Value for a switch case, and the
366 /// case's target basic block.
367 typedef std::pair<Constant*, MachineBasicBlock*> Case;
368 typedef std::vector<Case>::iterator CaseItr;
369 typedef std::pair<CaseItr, CaseItr> CaseRange;
370
371 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
372 /// of conditional branches.
373 struct CaseRec {
374 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
375 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
376
377 /// CaseBB - The MBB in which to emit the compare and branch
378 MachineBasicBlock *CaseBB;
379 /// LT, GE - If nonzero, we know the current case value must be less-than or
380 /// greater-than-or-equal-to these Constants.
381 Constant *LT;
382 Constant *GE;
383 /// Range - A pair of iterators representing the range of case values to be
384 /// processed at this point in the binary search tree.
385 CaseRange Range;
386 };
387
388 /// The comparison function for sorting Case values.
389 struct CaseCmp {
390 bool operator () (const Case& C1, const Case& C2) {
Reid Spencere63b6512006-12-31 05:55:36 +0000391 assert(isa<ConstantInt>(C1.first) && isa<ConstantInt>(C2.first));
Reid Spencer0917adf2007-01-03 04:25:33 +0000392 return cast<const ConstantInt>(C1.first)->getSExtValue() <
393 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000394 }
395 };
396
Chris Lattner7a60d912005-01-07 07:47:53 +0000397public:
398 // TLI - This is information that describes the available target features we
399 // need for lowering. This indicates when operations are unavailable,
400 // implemented with a libcall, etc.
401 TargetLowering &TLI;
402 SelectionDAG &DAG;
Owen Anderson20a631f2006-05-03 01:29:57 +0000403 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000404
Nate Begemaned728c12006-03-27 01:32:24 +0000405 /// SwitchCases - Vector of CaseBlock structures used to communicate
406 /// SwitchInst code generation information.
407 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000408 SelectionDAGISel::JumpTable JT;
Nate Begemaned728c12006-03-27 01:32:24 +0000409
Chris Lattner7a60d912005-01-07 07:47:53 +0000410 /// FuncInfo - Information about the function as a whole.
411 ///
412 FunctionLoweringInfo &FuncInfo;
413
414 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000415 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000416 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman866b4b42006-04-23 06:26:20 +0000417 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000418 }
419
Chris Lattner4108bb02005-01-17 19:43:36 +0000420 /// getRoot - Return the current virtual root of the Selection DAG.
421 ///
422 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000423 if (PendingLoads.empty())
424 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000425
Chris Lattner4d9651c2005-01-17 22:19:26 +0000426 if (PendingLoads.size() == 1) {
427 SDOperand Root = PendingLoads[0];
428 DAG.setRoot(Root);
429 PendingLoads.clear();
430 return Root;
431 }
432
433 // Otherwise, we have to make a token factor node.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000434 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
435 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000436 PendingLoads.clear();
437 DAG.setRoot(Root);
438 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000439 }
440
Chris Lattnered0110b2006-10-27 21:36:01 +0000441 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
442
Chris Lattner7a60d912005-01-07 07:47:53 +0000443 void visit(Instruction &I) { visit(I.getOpcode(), I); }
444
445 void visit(unsigned Opcode, User &I) {
Chris Lattnerd5e604d2006-11-10 04:41:34 +0000446 // Note: this doesn't use InstVisitor, because it has to work with
447 // ConstantExpr's in addition to instructions.
Chris Lattner7a60d912005-01-07 07:47:53 +0000448 switch (Opcode) {
449 default: assert(0 && "Unknown instruction type encountered!");
450 abort();
451 // Build the switch statement using the Instruction.def file.
452#define HANDLE_INST(NUM, OPCODE, CLASS) \
453 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
454#include "llvm/Instruction.def"
455 }
456 }
457
458 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
459
Chris Lattner4024c002006-03-15 22:19:46 +0000460 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000461 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000462 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000463
464 SDOperand getIntPtrConstant(uint64_t Val) {
465 return DAG.getConstant(Val, TLI.getPointerTy());
466 }
467
Chris Lattner8471b152006-03-16 19:57:50 +0000468 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-01-07 07:47:53 +0000469
470 const SDOperand &setValue(const Value *V, SDOperand NewN) {
471 SDOperand &N = NodeMap[V];
472 assert(N.Val == 0 && "Already set a value for this node!");
473 return N = NewN;
474 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000475
Chris Lattner6f87d182006-02-22 22:37:12 +0000476 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
477 MVT::ValueType VT,
478 bool OutReg, bool InReg,
479 std::set<unsigned> &OutputRegs,
480 std::set<unsigned> &InputRegs);
Nate Begemaned728c12006-03-27 01:32:24 +0000481
Chris Lattnered0110b2006-10-27 21:36:01 +0000482 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
483 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
484 unsigned Opc);
Chris Lattner84a03502006-10-27 23:50:33 +0000485 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000486 void ExportFromCurrentBlock(Value *V);
487
Chris Lattner7a60d912005-01-07 07:47:53 +0000488 // Terminator instructions.
489 void visitRet(ReturnInst &I);
490 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000491 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000492 void visitUnreachable(UnreachableInst &I) { /* noop */ }
493
Nate Begemaned728c12006-03-27 01:32:24 +0000494 // Helper for visitSwitch
495 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000496 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemaned728c12006-03-27 01:32:24 +0000497
Chris Lattner7a60d912005-01-07 07:47:53 +0000498 // These all get lowered before this pass.
Chris Lattner7a60d912005-01-07 07:47:53 +0000499 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
500 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
501
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000502 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
503 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000504 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000505 void visitAdd(User &I) {
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000506 if (I.getType()->isFloatingPoint())
507 visitFPBinary(I, ISD::FADD, ISD::VADD);
508 else
509 visitIntBinary(I, ISD::ADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000510 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000511 void visitSub(User &I);
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000512 void visitMul(User &I) {
513 if (I.getType()->isFloatingPoint())
514 visitFPBinary(I, ISD::FMUL, ISD::VMUL);
515 else
516 visitIntBinary(I, ISD::MUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000517 }
Reid Spencer7eb55b32006-11-02 01:53:59 +0000518 void visitURem(User &I) { visitIntBinary(I, ISD::UREM, 0); }
519 void visitSRem(User &I) { visitIntBinary(I, ISD::SREM, 0); }
520 void visitFRem(User &I) { visitFPBinary (I, ISD::FREM, 0); }
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000521 void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
522 void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
Reid Spencer7eb55b32006-11-02 01:53:59 +0000523 void visitFDiv(User &I) { visitFPBinary (I, ISD::FDIV, ISD::VSDIV); }
Reid Spencer7e80b0b2006-10-26 06:15:43 +0000524 void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
525 void visitOr (User &I) { visitIntBinary(I, ISD::OR, ISD::VOR); }
526 void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
Nate Begeman127321b2005-11-18 07:42:56 +0000527 void visitShl(User &I) { visitShift(I, ISD::SHL); }
Reid Spencerfdff9382006-11-08 06:47:33 +0000528 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
529 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencerd9436b62006-11-20 01:22:35 +0000530 void visitICmp(User &I);
531 void visitFCmp(User &I);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000532 // Visit the conversion instructions
533 void visitTrunc(User &I);
534 void visitZExt(User &I);
535 void visitSExt(User &I);
536 void visitFPTrunc(User &I);
537 void visitFPExt(User &I);
538 void visitFPToUI(User &I);
539 void visitFPToSI(User &I);
540 void visitUIToFP(User &I);
541 void visitSIToFP(User &I);
542 void visitPtrToInt(User &I);
543 void visitIntToPtr(User &I);
544 void visitBitCast(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000545
Chris Lattner67271862006-03-29 00:11:43 +0000546 void visitExtractElement(User &I);
547 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000548 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000549
Chris Lattner7a60d912005-01-07 07:47:53 +0000550 void visitGetElementPtr(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000551 void visitSelect(User &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000552
553 void visitMalloc(MallocInst &I);
554 void visitFree(FreeInst &I);
555 void visitAlloca(AllocaInst &I);
556 void visitLoad(LoadInst &I);
557 void visitStore(StoreInst &I);
558 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
559 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000560 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000561 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000562 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000563
Chris Lattner7a60d912005-01-07 07:47:53 +0000564 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000565 void visitVAArg(VAArgInst &I);
566 void visitVAEnd(CallInst &I);
567 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000568 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000569
Chris Lattner875def92005-01-11 05:56:49 +0000570 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000571
572 void visitUserOp1(Instruction &I) {
573 assert(0 && "UserOp1 should not exist at instruction selection time!");
574 abort();
575 }
576 void visitUserOp2(Instruction &I) {
577 assert(0 && "UserOp2 should not exist at instruction selection time!");
578 abort();
579 }
580};
581} // end namespace llvm
582
Chris Lattner8471b152006-03-16 19:57:50 +0000583SDOperand SelectionDAGLowering::getValue(const Value *V) {
584 SDOperand &N = NodeMap[V];
585 if (N.Val) return N;
586
587 const Type *VTy = V->getType();
588 MVT::ValueType VT = TLI.getValueType(VTy);
589 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
590 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
591 visit(CE->getOpcode(), *CE);
592 assert(N.Val && "visit didn't populate the ValueMap!");
593 return N;
594 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
595 return N = DAG.getGlobalAddress(GV, VT);
596 } else if (isa<ConstantPointerNull>(C)) {
597 return N = DAG.getConstant(0, TLI.getPointerTy());
598 } else if (isa<UndefValue>(C)) {
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000599 if (!isa<PackedType>(VTy))
600 return N = DAG.getNode(ISD::UNDEF, VT);
601
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000602 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000603 const PackedType *PTy = cast<PackedType>(VTy);
604 unsigned NumElements = PTy->getNumElements();
605 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
606
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000607 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000608 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
609
610 // Create a VConstant node with generic Vector type.
611 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
612 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000613 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
614 &Ops[0], Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000615 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
616 return N = DAG.getConstantFP(CFP->getValue(), VT);
617 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
618 unsigned NumElements = PTy->getNumElements();
619 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner8471b152006-03-16 19:57:50 +0000620
621 // Now that we know the number and type of the elements, push a
622 // Constant or ConstantFP node onto the ops list for each element of
623 // the packed constant.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000624 SmallVector<SDOperand, 8> Ops;
Chris Lattner8471b152006-03-16 19:57:50 +0000625 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000626 for (unsigned i = 0; i != NumElements; ++i)
627 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-03-16 19:57:50 +0000628 } else {
629 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
630 SDOperand Op;
631 if (MVT::isFloatingPoint(PVT))
632 Op = DAG.getConstantFP(0, PVT);
633 else
634 Op = DAG.getConstant(0, PVT);
635 Ops.assign(NumElements, Op);
636 }
637
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000638 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000639 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
640 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000641 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000642 } else {
643 // Canonicalize all constant ints to be unsigned.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000644 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000645 }
646 }
647
648 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
649 std::map<const AllocaInst*, int>::iterator SI =
650 FuncInfo.StaticAllocaMap.find(AI);
651 if (SI != FuncInfo.StaticAllocaMap.end())
652 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
653 }
654
655 std::map<const Value*, unsigned>::const_iterator VMI =
656 FuncInfo.ValueMap.find(V);
657 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
658
659 unsigned InReg = VMI->second;
660
661 // If this type is not legal, make it so now.
Chris Lattner5fe1f542006-03-31 02:06:56 +0000662 if (VT != MVT::Vector) {
Evan Cheng22cf8992006-12-13 20:57:08 +0000663 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner5fe1f542006-03-31 02:06:56 +0000664 // Source must be expanded. This input value is actually coming from the
665 // register pair VMI->second and VMI->second+1.
Evan Cheng22cf8992006-12-13 20:57:08 +0000666 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
667 unsigned NumVals = TLI.getNumElements(VT);
668 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
669 if (NumVals == 1)
670 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
671 else {
672 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
673 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
674 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
675 }
676 } else {
677 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
678 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
679 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
680 N = MVT::isFloatingPoint(VT)
681 ? DAG.getNode(ISD::FP_ROUND, VT, N)
682 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner8471b152006-03-16 19:57:50 +0000683 }
Chris Lattner5fe1f542006-03-31 02:06:56 +0000684 } else {
685 // Otherwise, if this is a vector, make it available as a generic vector
686 // here.
687 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner4a2413a2006-04-05 06:54:42 +0000688 const PackedType *PTy = cast<PackedType>(VTy);
689 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000690 PTyLegalElementVT);
691
692 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000693 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-03-31 02:06:56 +0000694 if (PTyElementVT == PTyLegalElementVT) {
695 // If the value types are legal, just VBUILD the CopyFromReg nodes.
696 for (unsigned i = 0; i != NE; ++i)
697 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
698 PTyElementVT));
699 } else if (PTyElementVT < PTyLegalElementVT) {
700 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
701 for (unsigned i = 0; i != NE; ++i) {
702 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
703 PTyElementVT);
704 if (MVT::isFloatingPoint(PTyElementVT))
705 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
706 else
707 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
708 Ops.push_back(Op);
709 }
710 } else {
711 // If the register was expanded, use BUILD_PAIR.
712 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
713 for (unsigned i = 0; i != NE/2; ++i) {
714 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
715 PTyElementVT);
716 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
717 PTyElementVT);
718 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
719 }
720 }
721
722 Ops.push_back(DAG.getConstant(NE, MVT::i32));
723 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000724 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-04-05 06:54:42 +0000725
726 // Finally, use a VBIT_CONVERT to make this available as the appropriate
727 // vector type.
728 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
729 DAG.getConstant(PTy->getNumElements(),
730 MVT::i32),
731 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner8471b152006-03-16 19:57:50 +0000732 }
733
734 return N;
735}
736
737
Chris Lattner7a60d912005-01-07 07:47:53 +0000738void SelectionDAGLowering::visitRet(ReturnInst &I) {
739 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000740 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000741 return;
742 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000743 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000744 NewValues.push_back(getRoot());
745 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
746 SDOperand RetOp = getValue(I.getOperand(i));
747
748 // If this is an integer return value, we need to promote it ourselves to
749 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
750 // than sign/zero.
Evan Chenga2e99532006-05-26 23:09:09 +0000751 // FIXME: C calling convention requires the return type to be promoted to
752 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000753 if (MVT::isInteger(RetOp.getValueType()) &&
754 RetOp.getValueType() < MVT::i64) {
755 MVT::ValueType TmpVT;
756 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
757 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
758 else
759 TmpVT = MVT::i32;
Reid Spencere63b6512006-12-31 05:55:36 +0000760 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencere6f81872007-01-03 16:49:33 +0000761 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer0917adf2007-01-03 04:25:33 +0000762 if (FTy->paramHasAttr(0, FunctionType::SExtAttribute))
763 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencere63b6512006-12-31 05:55:36 +0000764 if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
765 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer2a34b912007-01-03 05:03:05 +0000766 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000767 }
768 NewValues.push_back(RetOp);
Reid Spencere63b6512006-12-31 05:55:36 +0000769 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000770 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000771 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
772 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000773}
774
Chris Lattnered0110b2006-10-27 21:36:01 +0000775/// ExportFromCurrentBlock - If this condition isn't known to be exported from
776/// the current basic block, add it to ValueMap now so that we'll get a
777/// CopyTo/FromReg.
778void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
779 // No need to export constants.
780 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
781
782 // Already exported?
783 if (FuncInfo.isExportedInst(V)) return;
784
785 unsigned Reg = FuncInfo.InitializeRegForValue(V);
786 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
787}
788
Chris Lattner84a03502006-10-27 23:50:33 +0000789bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
790 const BasicBlock *FromBB) {
791 // The operands of the setcc have to be in this block. We don't know
792 // how to export them from some other block.
793 if (Instruction *VI = dyn_cast<Instruction>(V)) {
794 // Can export from current BB.
795 if (VI->getParent() == FromBB)
796 return true;
797
798 // Is already exported, noop.
799 return FuncInfo.isExportedInst(V);
800 }
801
802 // If this is an argument, we can export it if the BB is the entry block or
803 // if it is already exported.
804 if (isa<Argument>(V)) {
805 if (FromBB == &FromBB->getParent()->getEntryBlock())
806 return true;
807
808 // Otherwise, can only export this if it is already exported.
809 return FuncInfo.isExportedInst(V);
810 }
811
812 // Otherwise, constants can always be exported.
813 return true;
814}
815
Chris Lattnere60ae822006-10-29 21:01:20 +0000816static bool InBlock(const Value *V, const BasicBlock *BB) {
817 if (const Instruction *I = dyn_cast<Instruction>(V))
818 return I->getParent() == BB;
819 return true;
820}
821
Chris Lattnered0110b2006-10-27 21:36:01 +0000822/// FindMergedConditions - If Cond is an expression like
823void SelectionDAGLowering::FindMergedConditions(Value *Cond,
824 MachineBasicBlock *TBB,
825 MachineBasicBlock *FBB,
826 MachineBasicBlock *CurBB,
827 unsigned Opc) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000828 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencer266e42b2006-12-23 06:05:41 +0000829 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattnered0110b2006-10-27 21:36:01 +0000830
Reid Spencer266e42b2006-12-23 06:05:41 +0000831 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
832 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattnere60ae822006-10-29 21:01:20 +0000833 BOp->getParent() != CurBB->getBasicBlock() ||
834 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
835 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattnered0110b2006-10-27 21:36:01 +0000836 const BasicBlock *BB = CurBB->getBasicBlock();
837
Reid Spencer266e42b2006-12-23 06:05:41 +0000838 // If the leaf of the tree is a comparison, merge the condition into
839 // the caseblock.
840 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
841 // The operands of the cmp have to be in this block. We don't know
Chris Lattnerf31b9ef2006-10-29 18:23:37 +0000842 // how to export them from some other block. If this is the first block
843 // of the sequence, no exporting is needed.
844 (CurBB == CurMBB ||
845 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
846 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000847 BOp = cast<Instruction>(Cond);
848 ISD::CondCode Condition;
849 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
850 switch (IC->getPredicate()) {
851 default: assert(0 && "Unknown icmp predicate opcode!");
852 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
853 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
854 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
855 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
856 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
857 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
858 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
859 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
860 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
861 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
862 }
863 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
864 ISD::CondCode FPC, FOC;
865 switch (FC->getPredicate()) {
866 default: assert(0 && "Unknown fcmp predicate opcode!");
867 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
868 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
869 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
870 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
871 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
872 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
873 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
874 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
875 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
876 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
877 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
878 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
879 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
880 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
881 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
882 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
883 }
884 if (FiniteOnlyFPMath())
885 Condition = FOC;
886 else
887 Condition = FPC;
888 } else {
889 assert(0 && "Unknown compare instruction");
Chris Lattnered0110b2006-10-27 21:36:01 +0000890 }
891
Chris Lattnered0110b2006-10-27 21:36:01 +0000892 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
893 BOp->getOperand(1), TBB, FBB, CurBB);
894 SwitchCases.push_back(CB);
895 return;
896 }
897
898 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +0000899 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Chris Lattnered0110b2006-10-27 21:36:01 +0000900 TBB, FBB, CurBB);
901 SwitchCases.push_back(CB);
Chris Lattnered0110b2006-10-27 21:36:01 +0000902 return;
903 }
904
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000905
906 // Create TmpBB after CurBB.
Chris Lattnered0110b2006-10-27 21:36:01 +0000907 MachineFunction::iterator BBI = CurBB;
908 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
909 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
910
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000911 if (Opc == Instruction::Or) {
912 // Codegen X | Y as:
913 // jmp_if_X TBB
914 // jmp TmpBB
915 // TmpBB:
916 // jmp_if_Y TBB
917 // jmp FBB
918 //
Chris Lattnered0110b2006-10-27 21:36:01 +0000919
Chris Lattnerf1b54fd2006-10-27 21:54:23 +0000920 // Emit the LHS condition.
921 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
922
923 // Emit the RHS condition into TmpBB.
924 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
925 } else {
926 assert(Opc == Instruction::And && "Unknown merge op!");
927 // Codegen X & Y as:
928 // jmp_if_X TmpBB
929 // jmp FBB
930 // TmpBB:
931 // jmp_if_Y TBB
932 // jmp FBB
933 //
934 // This requires creation of TmpBB after CurBB.
935
936 // Emit the LHS condition.
937 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
938
939 // Emit the RHS condition into TmpBB.
940 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
941 }
Chris Lattnered0110b2006-10-27 21:36:01 +0000942}
943
Chris Lattner427301f2006-10-31 22:37:42 +0000944/// If the set of cases should be emitted as a series of branches, return true.
945/// If we should emit this as a bunch of and/or'd together conditions, return
946/// false.
947static bool
948ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
949 if (Cases.size() != 2) return true;
950
Chris Lattnerfe43bef2006-10-31 23:06:00 +0000951 // If this is two comparisons of the same values or'd or and'd together, they
952 // will get folded into a single comparison, so don't emit two blocks.
953 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
954 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
955 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
956 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
957 return false;
958 }
959
Chris Lattner427301f2006-10-31 22:37:42 +0000960 return true;
961}
962
Chris Lattner7a60d912005-01-07 07:47:53 +0000963void SelectionDAGLowering::visitBr(BranchInst &I) {
964 // Update machine-CFG edges.
965 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000966
967 // Figure out which block is immediately after the current one.
968 MachineBasicBlock *NextBlock = 0;
969 MachineFunction::iterator BBI = CurMBB;
970 if (++BBI != CurMBB->getParent()->end())
971 NextBlock = BBI;
972
973 if (I.isUnconditional()) {
974 // If this is not a fall-through branch, emit the branch.
975 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000976 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000977 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000978
Chris Lattner963ddad2006-10-24 17:57:59 +0000979 // Update machine-CFG edges.
980 CurMBB->addSuccessor(Succ0MBB);
981
982 return;
983 }
984
985 // If this condition is one of the special cases we handle, do special stuff
986 // now.
987 Value *CondVal = I.getCondition();
Chris Lattner963ddad2006-10-24 17:57:59 +0000988 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattnered0110b2006-10-27 21:36:01 +0000989
990 // If this is a series of conditions that are or'd or and'd together, emit
991 // this as a sequence of branches instead of setcc's with and/or operations.
992 // For example, instead of something like:
993 // cmp A, B
994 // C = seteq
995 // cmp D, E
996 // F = setle
997 // or C, F
998 // jnz foo
999 // Emit:
1000 // cmp A, B
1001 // je foo
1002 // cmp D, E
1003 // jle foo
1004 //
1005 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1006 if (BOp->hasOneUse() &&
Chris Lattnerf1b54fd2006-10-27 21:54:23 +00001007 (BOp->getOpcode() == Instruction::And ||
Chris Lattnered0110b2006-10-27 21:36:01 +00001008 BOp->getOpcode() == Instruction::Or)) {
1009 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001010 // If the compares in later blocks need to use values not currently
1011 // exported from this block, export them now. This block should always
1012 // be the first entry.
1013 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1014
Chris Lattner427301f2006-10-31 22:37:42 +00001015 // Allow some cases to be rejected.
1016 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattner427301f2006-10-31 22:37:42 +00001017 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1018 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1019 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1020 }
1021
1022 // Emit the branch for this block.
1023 visitSwitchCase(SwitchCases[0]);
1024 SwitchCases.erase(SwitchCases.begin());
1025 return;
Chris Lattnerf31b9ef2006-10-29 18:23:37 +00001026 }
1027
Chris Lattnerfe43bef2006-10-31 23:06:00 +00001028 // Okay, we decided not to do this, remove any inserted MBB's and clear
1029 // SwitchCases.
1030 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1031 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1032
Chris Lattner427301f2006-10-31 22:37:42 +00001033 SwitchCases.clear();
Chris Lattnered0110b2006-10-27 21:36:01 +00001034 }
1035 }
Chris Lattner61bcf912006-10-24 18:07:37 +00001036
1037 // Create a CaseBlock record representing this branch.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001038 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Chris Lattner61bcf912006-10-24 18:07:37 +00001039 Succ0MBB, Succ1MBB, CurMBB);
1040 // Use visitSwitchCase to actually insert the fast branch sequence for this
1041 // cond branch.
1042 visitSwitchCase(CB);
Chris Lattner7a60d912005-01-07 07:47:53 +00001043}
1044
Nate Begemaned728c12006-03-27 01:32:24 +00001045/// visitSwitchCase - Emits the necessary code to represent a single node in
1046/// the binary search tree resulting from lowering a switch instruction.
1047void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001048 SDOperand Cond;
1049 SDOperand CondLHS = getValue(CB.CmpLHS);
1050
Chris Lattnered0110b2006-10-27 21:36:01 +00001051 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1052 // handle common cases produced by branch lowering.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001053 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner963ddad2006-10-24 17:57:59 +00001054 Cond = CondLHS;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001055 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Chris Lattnered0110b2006-10-27 21:36:01 +00001056 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1057 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1058 } else
1059 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemaned728c12006-03-27 01:32:24 +00001060
1061 // Set NextBlock to be the MBB immediately after the current one, if any.
1062 // This is used to avoid emitting unnecessary branches to the next block.
1063 MachineBasicBlock *NextBlock = 0;
1064 MachineFunction::iterator BBI = CurMBB;
1065 if (++BBI != CurMBB->getParent()->end())
1066 NextBlock = BBI;
1067
1068 // If the lhs block is the next block, invert the condition so that we can
1069 // fall through to the lhs instead of the rhs block.
Chris Lattner963ddad2006-10-24 17:57:59 +00001070 if (CB.TrueBB == NextBlock) {
1071 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001072 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1073 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1074 }
1075 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001076 DAG.getBasicBlock(CB.TrueBB));
1077 if (CB.FalseBB == NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001078 DAG.setRoot(BrCond);
1079 else
1080 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner963ddad2006-10-24 17:57:59 +00001081 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemaned728c12006-03-27 01:32:24 +00001082 // Update successor info
Chris Lattner963ddad2006-10-24 17:57:59 +00001083 CurMBB->addSuccessor(CB.TrueBB);
1084 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001085}
1086
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001087void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001088 // Emit the code for the jump table
1089 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng84a28d42006-10-30 08:00:44 +00001090 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1091 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1092 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1093 Table, Index));
1094 return;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001095}
1096
Nate Begemaned728c12006-03-27 01:32:24 +00001097void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1098 // Figure out which block is immediately after the current one.
1099 MachineBasicBlock *NextBlock = 0;
1100 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001101
Nate Begemaned728c12006-03-27 01:32:24 +00001102 if (++BBI != CurMBB->getParent()->end())
1103 NextBlock = BBI;
1104
Chris Lattner6d6fc262006-10-22 21:36:53 +00001105 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1106
Nate Begemaned728c12006-03-27 01:32:24 +00001107 // If there is only the default destination, branch to it if it is not the
1108 // next basic block. Otherwise, just fall through.
1109 if (I.getNumOperands() == 2) {
1110 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001111
Nate Begemaned728c12006-03-27 01:32:24 +00001112 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +00001113 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +00001114 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +00001115 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001116
Chris Lattner6d6fc262006-10-22 21:36:53 +00001117 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +00001118 return;
1119 }
1120
1121 // If there are any non-default case statements, create a vector of Cases
1122 // representing each one, and sort the vector so that we can efficiently
1123 // create a binary search tree from them.
1124 std::vector<Case> Cases;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001125
Nate Begemaned728c12006-03-27 01:32:24 +00001126 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1127 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1128 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1129 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001130
Nate Begemaned728c12006-03-27 01:32:24 +00001131 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1132
1133 // Get the Value to be switched on and default basic blocks, which will be
1134 // inserted into CaseBlock records, representing basic blocks in the binary
1135 // search tree.
1136 Value *SV = I.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001137
1138 // Get the MachineFunction which holds the current MBB. This is used during
1139 // emission of jump tables, and when inserting any additional MBBs necessary
1140 // to represent the switch.
Nate Begemaned728c12006-03-27 01:32:24 +00001141 MachineFunction *CurMF = CurMBB->getParent();
1142 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattner6d6fc262006-10-22 21:36:53 +00001143
1144 // If the switch has few cases (two or less) emit a series of specific
1145 // tests.
Chris Lattner76a7bc82006-10-22 23:00:53 +00001146 if (Cases.size() < 3) {
Chris Lattner6d6fc262006-10-22 21:36:53 +00001147 // TODO: If any two of the cases has the same destination, and if one value
1148 // is the same as the other, but has one bit unset that the other has set,
1149 // use bit manipulation to do two compares at once. For example:
1150 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1151
Chris Lattner4c931502006-10-23 18:38:22 +00001152 // Rearrange the case blocks so that the last one falls through if possible.
1153 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1154 // The last case block won't fall through into 'NextBlock' if we emit the
1155 // branches in this order. See if rearranging a case value would help.
1156 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1157 if (Cases[i].second == NextBlock) {
1158 std::swap(Cases[i], Cases.back());
1159 break;
1160 }
1161 }
1162 }
1163
Chris Lattner6d6fc262006-10-22 21:36:53 +00001164 // Create a CaseBlock record representing a conditional branch to
1165 // the Case's target mbb if the value being switched on SV is equal
1166 // to C.
1167 MachineBasicBlock *CurBlock = CurMBB;
1168 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1169 MachineBasicBlock *FallThrough;
1170 if (i != e-1) {
1171 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1172 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1173 } else {
1174 // If the last case doesn't match, go to the default block.
1175 FallThrough = Default;
1176 }
1177
1178 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1179 Cases[i].second, FallThrough, CurBlock);
1180
1181 // If emitting the first comparison, just call visitSwitchCase to emit the
1182 // code into the current block. Otherwise, push the CaseBlock onto the
1183 // vector to be later processed by SDISel, and insert the node's MBB
1184 // before the next MBB.
1185 if (CurBlock == CurMBB)
1186 visitSwitchCase(CB);
1187 else
1188 SwitchCases.push_back(CB);
1189
1190 CurBlock = FallThrough;
1191 }
1192 return;
1193 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001194
Nate Begemand7a19102006-05-08 16:51:36 +00001195 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1196 // target supports indirect branches, then emit a jump table rather than
1197 // lowering the switch to a binary tree of conditional branches.
Evan Cheng84a28d42006-10-30 08:00:44 +00001198 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1199 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemandf488392006-05-03 03:48:02 +00001200 Cases.size() > 5) {
Zhou Sheng75b871f2007-01-11 12:24:14 +00001201 uint64_t First =cast<ConstantInt>(Cases.front().first)->getZExtValue();
1202 uint64_t Last = cast<ConstantInt>(Cases.back().first)->getZExtValue();
Nate Begemandf488392006-05-03 03:48:02 +00001203 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1204
Nate Begemand7a19102006-05-08 16:51:36 +00001205 if (Density >= 0.3125) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001206 // Create a new basic block to hold the code for loading the address
1207 // of the jump table, and jumping to it. Update successor information;
1208 // we will either branch to the default case for the switch, or the jump
1209 // table.
1210 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1211 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1212 CurMBB->addSuccessor(Default);
1213 CurMBB->addSuccessor(JumpTableBB);
1214
1215 // Subtract the lowest switch case value from the value being switched on
1216 // and conditional branch to default mbb if the result is greater than the
1217 // difference between smallest and largest cases.
1218 SDOperand SwitchOp = getValue(SV);
1219 MVT::ValueType VT = SwitchOp.getValueType();
1220 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1221 DAG.getConstant(First, VT));
1222
1223 // The SDNode we just created, which holds the value being switched on
1224 // minus the the smallest case value, needs to be copied to a virtual
1225 // register so it can be used as an index into the jump table in a
1226 // subsequent basic block. This value may be smaller or larger than the
1227 // target's pointer type, and therefore require extension or truncating.
1228 if (VT > TLI.getPointerTy())
1229 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1230 else
1231 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001232
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001233 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1234 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1235
1236 // Emit the range check for the jump table, and branch to the default
1237 // block for the switch statement if the value being switched on exceeds
1238 // the largest case in the switch.
1239 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1240 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1241 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1242 DAG.getBasicBlock(Default)));
1243
Nate Begemandf488392006-05-03 03:48:02 +00001244 // Build a vector of destination BBs, corresponding to each target
1245 // of the jump table. If the value of the jump table slot corresponds to
1246 // a case statement, push the case's BB onto the vector, otherwise, push
1247 // the default BB.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001248 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemandf488392006-05-03 03:48:02 +00001249 uint64_t TEI = First;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001250 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Zhou Sheng75b871f2007-01-11 12:24:14 +00001251 if (cast<ConstantInt>(ii->first)->getZExtValue() == TEI) {
Nate Begemandf488392006-05-03 03:48:02 +00001252 DestBBs.push_back(ii->second);
Nate Begemandf488392006-05-03 03:48:02 +00001253 ++ii;
1254 } else {
1255 DestBBs.push_back(Default);
Nate Begemandf488392006-05-03 03:48:02 +00001256 }
Nate Begemandf488392006-05-03 03:48:02 +00001257
Chris Lattner84a03502006-10-27 23:50:33 +00001258 // Update successor info. Add one edge to each unique successor.
1259 // Vector bool would be better, but vector<bool> is really slow.
1260 std::vector<unsigned char> SuccsHandled;
1261 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1262
Chris Lattner2e0dfb02006-09-10 06:36:57 +00001263 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner84a03502006-10-27 23:50:33 +00001264 E = DestBBs.end(); I != E; ++I) {
1265 if (!SuccsHandled[(*I)->getNumber()]) {
1266 SuccsHandled[(*I)->getNumber()] = true;
1267 JumpTableBB->addSuccessor(*I);
1268 }
1269 }
Nate Begemandf488392006-05-03 03:48:02 +00001270
1271 // Create a jump table index for this jump table, or return an existing
1272 // one.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001273 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1274
1275 // Set the jump table information so that we can codegen it as a second
1276 // MachineBasicBlock
1277 JT.Reg = JumpTableReg;
1278 JT.JTI = JTI;
1279 JT.MBB = JumpTableBB;
Nate Begeman866b4b42006-04-23 06:26:20 +00001280 JT.Default = Default;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001281 return;
1282 }
1283 }
Nate Begemaned728c12006-03-27 01:32:24 +00001284
1285 // Push the initial CaseRec onto the worklist
1286 std::vector<CaseRec> CaseVec;
1287 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1288
1289 while (!CaseVec.empty()) {
1290 // Grab a record representing a case range to process off the worklist
1291 CaseRec CR = CaseVec.back();
1292 CaseVec.pop_back();
1293
1294 // Size is the number of Cases represented by this range. If Size is 1,
1295 // then we are processing a leaf of the binary search tree. Otherwise,
1296 // we need to pick a pivot, and push left and right ranges onto the
1297 // worklist.
1298 unsigned Size = CR.Range.second - CR.Range.first;
1299
1300 if (Size == 1) {
1301 // Create a CaseBlock record representing a conditional branch to
1302 // the Case's target mbb if the value being switched on SV is equal
1303 // to C. Otherwise, branch to default.
1304 Constant *C = CR.Range.first->first;
1305 MachineBasicBlock *Target = CR.Range.first->second;
1306 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1307 CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001308
Nate Begemaned728c12006-03-27 01:32:24 +00001309 // If the MBB representing the leaf node is the current MBB, then just
1310 // call visitSwitchCase to emit the code into the current block.
1311 // Otherwise, push the CaseBlock onto the vector to be later processed
1312 // by SDISel, and insert the node's MBB before the next MBB.
1313 if (CR.CaseBB == CurMBB)
1314 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001315 else
Nate Begemaned728c12006-03-27 01:32:24 +00001316 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001317 } else {
1318 // split case range at pivot
1319 CaseItr Pivot = CR.Range.first + (Size / 2);
1320 CaseRange LHSR(CR.Range.first, Pivot);
1321 CaseRange RHSR(Pivot, CR.Range.second);
1322 Constant *C = Pivot->first;
Chris Lattner963ddad2006-10-24 17:57:59 +00001323 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001324
Nate Begemaned728c12006-03-27 01:32:24 +00001325 // We know that we branch to the LHS if the Value being switched on is
1326 // less than the Pivot value, C. We use this to optimize our binary
1327 // tree a bit, by recognizing that if SV is greater than or equal to the
1328 // LHS's Case Value, and that Case Value is exactly one less than the
1329 // Pivot's Value, then we can branch directly to the LHS's Target,
1330 // rather than creating a leaf node for it.
1331 if ((LHSR.second - LHSR.first) == 1 &&
1332 LHSR.first->first == CR.GE &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00001333 cast<ConstantInt>(C)->getZExtValue() ==
1334 (cast<ConstantInt>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001335 TrueBB = LHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001336 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001337 TrueBB = new MachineBasicBlock(LLVMBB);
1338 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1339 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001340 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001341
Nate Begemaned728c12006-03-27 01:32:24 +00001342 // Similar to the optimization above, if the Value being switched on is
1343 // known to be less than the Constant CR.LT, and the current Case Value
1344 // is CR.LT - 1, then we can branch directly to the target block for
1345 // the current Case Value, rather than emitting a RHS leaf node for it.
1346 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Zhou Sheng75b871f2007-01-11 12:24:14 +00001347 cast<ConstantInt>(RHSR.first->first)->getZExtValue() ==
1348 (cast<ConstantInt>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner963ddad2006-10-24 17:57:59 +00001349 FalseBB = RHSR.first->second;
Nate Begemaned728c12006-03-27 01:32:24 +00001350 } else {
Chris Lattner963ddad2006-10-24 17:57:59 +00001351 FalseBB = new MachineBasicBlock(LLVMBB);
1352 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1353 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemaned728c12006-03-27 01:32:24 +00001354 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001355
Nate Begemaned728c12006-03-27 01:32:24 +00001356 // Create a CaseBlock record representing a conditional branch to
1357 // the LHS node if the value being switched on SV is less than C.
1358 // Otherwise, branch to LHS.
Reid Spencer0917adf2007-01-03 04:25:33 +00001359 ISD::CondCode CC = ISD::SETLT;
Chris Lattner963ddad2006-10-24 17:57:59 +00001360 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001361
Nate Begemaned728c12006-03-27 01:32:24 +00001362 if (CR.CaseBB == CurMBB)
1363 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001364 else
Nate Begemaned728c12006-03-27 01:32:24 +00001365 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001366 }
1367 }
1368}
1369
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001370void SelectionDAGLowering::visitSub(User &I) {
1371 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +00001372 if (I.getType()->isFloatingPoint()) {
1373 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1374 if (CFP->isExactlyValue(-0.0)) {
1375 SDOperand Op2 = getValue(I.getOperand(1));
1376 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1377 return;
1378 }
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001379 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1380 } else
1381 visitIntBinary(I, ISD::SUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001382}
1383
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001384void
1385SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001386 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001387 SDOperand Op1 = getValue(I.getOperand(0));
1388 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +00001389
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001390 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Chris Lattner32206f52006-03-18 01:44:44 +00001391 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1392 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1393 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Reid Spencer7e80b0b2006-10-26 06:15:43 +00001394 } else {
1395 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1396 }
1397}
1398
1399void
1400SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1401 const Type *Ty = I.getType();
1402 SDOperand Op1 = getValue(I.getOperand(0));
1403 SDOperand Op2 = getValue(I.getOperand(1));
1404
1405 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1406 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1407 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1408 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1409 } else {
1410 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001411 }
Nate Begeman127321b2005-11-18 07:42:56 +00001412}
Chris Lattner96c26752005-01-19 22:31:21 +00001413
Nate Begeman127321b2005-11-18 07:42:56 +00001414void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1415 SDOperand Op1 = getValue(I.getOperand(0));
1416 SDOperand Op2 = getValue(I.getOperand(1));
1417
1418 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1419
Chris Lattner7a60d912005-01-07 07:47:53 +00001420 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1421}
1422
Reid Spencerd9436b62006-11-20 01:22:35 +00001423void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001424 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1425 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1426 predicate = IC->getPredicate();
1427 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1428 predicate = ICmpInst::Predicate(IC->getPredicate());
1429 SDOperand Op1 = getValue(I.getOperand(0));
1430 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencerd9436b62006-11-20 01:22:35 +00001431 ISD::CondCode Opcode;
Reid Spencer266e42b2006-12-23 06:05:41 +00001432 switch (predicate) {
Reid Spencerd9436b62006-11-20 01:22:35 +00001433 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1434 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1435 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1436 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1437 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1438 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1439 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1440 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1441 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1442 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1443 default:
1444 assert(!"Invalid ICmp predicate value");
1445 Opcode = ISD::SETEQ;
1446 break;
1447 }
1448 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1449}
1450
1451void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001452 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1453 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1454 predicate = FC->getPredicate();
1455 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1456 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner7a60d912005-01-07 07:47:53 +00001457 SDOperand Op1 = getValue(I.getOperand(0));
1458 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer266e42b2006-12-23 06:05:41 +00001459 ISD::CondCode Condition, FOC, FPC;
1460 switch (predicate) {
1461 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1462 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1463 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1464 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1465 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1466 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1467 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1468 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1469 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1470 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1471 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1472 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1473 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1474 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1475 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1476 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1477 default:
1478 assert(!"Invalid FCmp predicate value");
1479 FOC = FPC = ISD::SETFALSE;
1480 break;
1481 }
1482 if (FiniteOnlyFPMath())
1483 Condition = FOC;
1484 else
1485 Condition = FPC;
1486 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner7a60d912005-01-07 07:47:53 +00001487}
1488
1489void SelectionDAGLowering::visitSelect(User &I) {
1490 SDOperand Cond = getValue(I.getOperand(0));
1491 SDOperand TrueVal = getValue(I.getOperand(1));
1492 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattner02274a52006-04-08 22:22:57 +00001493 if (!isa<PackedType>(I.getType())) {
1494 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1495 TrueVal, FalseVal));
1496 } else {
1497 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1498 *(TrueVal.Val->op_end()-2),
1499 *(TrueVal.Val->op_end()-1)));
1500 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001501}
1502
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001503
1504void SelectionDAGLowering::visitTrunc(User &I) {
1505 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1506 SDOperand N = getValue(I.getOperand(0));
1507 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1508 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1509}
1510
1511void SelectionDAGLowering::visitZExt(User &I) {
1512 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1513 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1514 SDOperand N = getValue(I.getOperand(0));
1515 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1516 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1517}
1518
1519void SelectionDAGLowering::visitSExt(User &I) {
1520 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1521 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1522 SDOperand N = getValue(I.getOperand(0));
1523 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1524 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1525}
1526
1527void SelectionDAGLowering::visitFPTrunc(User &I) {
1528 // FPTrunc is never a no-op cast, no need to check
1529 SDOperand N = getValue(I.getOperand(0));
1530 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1531 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1532}
1533
1534void SelectionDAGLowering::visitFPExt(User &I){
1535 // FPTrunc is never a no-op cast, no need to check
1536 SDOperand N = getValue(I.getOperand(0));
1537 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1538 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1539}
1540
1541void SelectionDAGLowering::visitFPToUI(User &I) {
1542 // FPToUI is never a no-op cast, no need to check
1543 SDOperand N = getValue(I.getOperand(0));
1544 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1545 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1546}
1547
1548void SelectionDAGLowering::visitFPToSI(User &I) {
1549 // FPToSI is never a no-op cast, no need to check
1550 SDOperand N = getValue(I.getOperand(0));
1551 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1552 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1553}
1554
1555void SelectionDAGLowering::visitUIToFP(User &I) {
1556 // UIToFP is never a no-op cast, no need to check
1557 SDOperand N = getValue(I.getOperand(0));
1558 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1559 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1560}
1561
1562void SelectionDAGLowering::visitSIToFP(User &I){
1563 // UIToFP is never a no-op cast, no need to check
1564 SDOperand N = getValue(I.getOperand(0));
1565 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1566 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1567}
1568
1569void SelectionDAGLowering::visitPtrToInt(User &I) {
1570 // What to do depends on the size of the integer and the size of the pointer.
1571 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner7a60d912005-01-07 07:47:53 +00001572 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001573 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001574 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001575 SDOperand Result;
1576 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1577 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1578 else
1579 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1580 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1581 setValue(&I, Result);
1582}
Chris Lattner7a60d912005-01-07 07:47:53 +00001583
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001584void SelectionDAGLowering::visitIntToPtr(User &I) {
1585 // What to do depends on the size of the integer and the size of the pointer.
1586 // We can either truncate, zero extend, or no-op, accordingly.
1587 SDOperand N = getValue(I.getOperand(0));
1588 MVT::ValueType SrcVT = N.getValueType();
1589 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1590 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1591 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1592 else
1593 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1594 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1595}
1596
1597void SelectionDAGLowering::visitBitCast(User &I) {
1598 SDOperand N = getValue(I.getOperand(0));
1599 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner2f4119a2006-03-22 20:09:35 +00001600 if (DestVT == MVT::Vector) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001601 // This is a cast to a vector from something else.
1602 // Get information about the output vector.
Chris Lattner2f4119a2006-03-22 20:09:35 +00001603 const PackedType *DestTy = cast<PackedType>(I.getType());
1604 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1605 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1606 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1607 DAG.getValueType(EltVT)));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001608 return;
1609 }
1610 MVT::ValueType SrcVT = N.getValueType();
1611 if (SrcVT == MVT::Vector) {
1612 // This is a cast from a vctor to something else.
1613 // Get information about the input vector.
Chris Lattner2f4119a2006-03-22 20:09:35 +00001614 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001615 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00001616 }
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001617
1618 // BitCast assures us that source and destination are the same size so this
1619 // is either a BIT_CONVERT or a no-op.
1620 if (DestVT != N.getValueType())
1621 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1622 else
1623 setValue(&I, N); // noop cast.
Chris Lattner7a60d912005-01-07 07:47:53 +00001624}
1625
Chris Lattner67271862006-03-29 00:11:43 +00001626void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001627 SDOperand InVec = getValue(I.getOperand(0));
1628 SDOperand InVal = getValue(I.getOperand(1));
1629 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1630 getValue(I.getOperand(2)));
1631
Chris Lattner29b23012006-03-19 01:17:20 +00001632 SDOperand Num = *(InVec.Val->op_end()-2);
1633 SDOperand Typ = *(InVec.Val->op_end()-1);
1634 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1635 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001636}
1637
Chris Lattner67271862006-03-29 00:11:43 +00001638void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001639 SDOperand InVec = getValue(I.getOperand(0));
1640 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1641 getValue(I.getOperand(1)));
1642 SDOperand Typ = *(InVec.Val->op_end()-1);
1643 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1644 TLI.getValueType(I.getType()), InVec, InIdx));
1645}
Chris Lattner32206f52006-03-18 01:44:44 +00001646
Chris Lattner098c01e2006-04-08 04:15:24 +00001647void SelectionDAGLowering::visitShuffleVector(User &I) {
1648 SDOperand V1 = getValue(I.getOperand(0));
1649 SDOperand V2 = getValue(I.getOperand(1));
1650 SDOperand Mask = getValue(I.getOperand(2));
1651
1652 SDOperand Num = *(V1.Val->op_end()-2);
1653 SDOperand Typ = *(V2.Val->op_end()-1);
1654 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1655 V1, V2, Mask, Num, Typ));
1656}
1657
1658
Chris Lattner7a60d912005-01-07 07:47:53 +00001659void SelectionDAGLowering::visitGetElementPtr(User &I) {
1660 SDOperand N = getValue(I.getOperand(0));
1661 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001662
1663 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1664 OI != E; ++OI) {
1665 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001666 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001667 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00001668 if (Field) {
1669 // N = N + Offset
Owen Anderson20a631f2006-05-03 01:29:57 +00001670 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner7a60d912005-01-07 07:47:53 +00001671 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001672 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001673 }
1674 Ty = StTy->getElementType(Field);
1675 } else {
1676 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001677
Chris Lattner43535a12005-11-09 04:45:33 +00001678 // If this is a constant subscript, handle it quickly.
1679 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001680 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00001681 uint64_t Offs =
Evan Cheng8ec52832007-01-05 01:46:20 +00001682 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001683 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1684 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001685 }
Chris Lattner43535a12005-11-09 04:45:33 +00001686
1687 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001688 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001689 SDOperand IdxN = getValue(Idx);
1690
1691 // If the index is smaller or larger than intptr_t, truncate or extend
1692 // it.
1693 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencere63b6512006-12-31 05:55:36 +00001694 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner43535a12005-11-09 04:45:33 +00001695 } else if (IdxN.getValueType() > N.getValueType())
1696 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1697
1698 // If this is a multiply by a power of two, turn it into a shl
1699 // immediately. This is a very common case.
1700 if (isPowerOf2_64(ElementSize)) {
1701 unsigned Amt = Log2_64(ElementSize);
1702 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001703 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001704 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1705 continue;
1706 }
1707
1708 SDOperand Scale = getIntPtrConstant(ElementSize);
1709 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1710 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001711 }
1712 }
1713 setValue(&I, N);
1714}
1715
1716void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1717 // If this is a fixed sized alloca in the entry block of the function,
1718 // allocate it statically on the stack.
1719 if (FuncInfo.StaticAllocaMap.count(&I))
1720 return; // getValue will auto-populate this.
1721
1722 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001723 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner50ee0e42007-01-20 22:35:55 +00001724 unsigned Align =
1725 std::max((unsigned)TLI.getTargetData()->getTypeAlignmentPref(Ty),
1726 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001727
1728 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001729 MVT::ValueType IntPtr = TLI.getPointerTy();
1730 if (IntPtr < AllocSize.getValueType())
1731 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1732 else if (IntPtr > AllocSize.getValueType())
1733 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001734
Chris Lattnereccb73d2005-01-22 23:04:37 +00001735 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001736 getIntPtrConstant(TySize));
1737
1738 // Handle alignment. If the requested alignment is less than or equal to the
1739 // stack alignment, ignore it and round the size of the allocation up to the
1740 // stack alignment size. If the size is greater than the stack alignment, we
1741 // note this in the DYNAMIC_STACKALLOC node.
1742 unsigned StackAlign =
1743 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1744 if (Align <= StackAlign) {
1745 Align = 0;
1746 // Add SA-1 to the size.
1747 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1748 getIntPtrConstant(StackAlign-1));
1749 // Mask out the low bits for alignment purposes.
1750 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1751 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1752 }
1753
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001754 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00001755 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1756 MVT::Other);
1757 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner7a60d912005-01-07 07:47:53 +00001758 DAG.setRoot(setValue(&I, DSA).getValue(1));
1759
1760 // Inform the Frame Information that we have just allocated a variable-sized
1761 // object.
1762 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1763}
1764
Chris Lattner7a60d912005-01-07 07:47:53 +00001765void SelectionDAGLowering::visitLoad(LoadInst &I) {
1766 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001767
Chris Lattner4d9651c2005-01-17 22:19:26 +00001768 SDOperand Root;
1769 if (I.isVolatile())
1770 Root = getRoot();
1771 else {
1772 // Do not serialize non-volatile loads against each other.
1773 Root = DAG.getRoot();
1774 }
Chris Lattner4024c002006-03-15 22:19:46 +00001775
Evan Chenge71fe34d2006-10-09 20:57:25 +00001776 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00001777 Root, I.isVolatile()));
1778}
1779
1780SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001781 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00001782 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001783 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001784 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001785 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00001786 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1787 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001788 } else {
Evan Cheng258657e2006-12-20 01:27:29 +00001789 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001790 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001791
Chris Lattner4024c002006-03-15 22:19:46 +00001792 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001793 DAG.setRoot(L.getValue(1));
1794 else
1795 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001796
1797 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001798}
1799
1800
1801void SelectionDAGLowering::visitStore(StoreInst &I) {
1802 Value *SrcV = I.getOperand(0);
1803 SDOperand Src = getValue(SrcV);
1804 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng258657e2006-12-20 01:27:29 +00001805 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Chengab51cf22006-10-13 21:14:26 +00001806 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00001807}
1808
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001809/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1810/// access memory and has no other side effects at all.
1811static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1812#define GET_NO_MEMORY_INTRINSICS
1813#include "llvm/Intrinsics.gen"
1814#undef GET_NO_MEMORY_INTRINSICS
1815 return false;
1816}
1817
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001818// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1819// have any side-effects or if it only reads memory.
1820static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1821#define GET_SIDE_EFFECT_INFO
1822#include "llvm/Intrinsics.gen"
1823#undef GET_SIDE_EFFECT_INFO
1824 return false;
1825}
1826
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001827/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1828/// node.
1829void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1830 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001831 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001832 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001833
1834 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001835 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001836 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1837 if (OnlyLoad) {
1838 // We don't need to serialize loads against other loads.
1839 Ops.push_back(DAG.getRoot());
1840 } else {
1841 Ops.push_back(getRoot());
1842 }
1843 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001844
1845 // Add the intrinsic ID as an integer operand.
1846 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1847
1848 // Add all operands of the call to the operand list.
1849 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1850 SDOperand Op = getValue(I.getOperand(i));
1851
1852 // If this is a vector type, force it to the right packed type.
1853 if (Op.getValueType() == MVT::Vector) {
1854 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1855 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1856
1857 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1858 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1859 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1860 }
1861
1862 assert(TLI.isTypeLegal(Op.getValueType()) &&
1863 "Intrinsic uses a non-legal type?");
1864 Ops.push_back(Op);
1865 }
1866
1867 std::vector<MVT::ValueType> VTs;
1868 if (I.getType() != Type::VoidTy) {
1869 MVT::ValueType VT = TLI.getValueType(I.getType());
1870 if (VT == MVT::Vector) {
1871 const PackedType *DestTy = cast<PackedType>(I.getType());
1872 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1873
1874 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1875 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1876 }
1877
1878 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1879 VTs.push_back(VT);
1880 }
1881 if (HasChain)
1882 VTs.push_back(MVT::Other);
1883
Chris Lattnerbd887772006-08-14 23:53:35 +00001884 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1885
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001886 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001887 SDOperand Result;
1888 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00001889 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1890 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001891 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00001892 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1893 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001894 else
Chris Lattnerbd887772006-08-14 23:53:35 +00001895 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1896 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001897
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001898 if (HasChain) {
1899 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1900 if (OnlyLoad)
1901 PendingLoads.push_back(Chain);
1902 else
1903 DAG.setRoot(Chain);
1904 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001905 if (I.getType() != Type::VoidTy) {
1906 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1907 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1908 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1909 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1910 DAG.getValueType(EVT));
1911 }
1912 setValue(&I, Result);
1913 }
1914}
1915
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001916/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1917/// we want to emit this as a call to a named external function, return the name
1918/// otherwise lower it and return null.
1919const char *
1920SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1921 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001922 default:
1923 // By default, turn this into a target intrinsic node.
1924 visitTargetIntrinsic(I, Intrinsic);
1925 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001926 case Intrinsic::vastart: visitVAStart(I); return 0;
1927 case Intrinsic::vaend: visitVAEnd(I); return 0;
1928 case Intrinsic::vacopy: visitVACopy(I); return 0;
1929 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1930 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1931 case Intrinsic::setjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00001932 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001933 break;
1934 case Intrinsic::longjmp:
Anton Korobeynikov3b7c2572006-12-10 23:12:42 +00001935 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001936 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001937 case Intrinsic::memcpy_i32:
1938 case Intrinsic::memcpy_i64:
1939 visitMemIntrinsic(I, ISD::MEMCPY);
1940 return 0;
1941 case Intrinsic::memset_i32:
1942 case Intrinsic::memset_i64:
1943 visitMemIntrinsic(I, ISD::MEMSET);
1944 return 0;
1945 case Intrinsic::memmove_i32:
1946 case Intrinsic::memmove_i64:
1947 visitMemIntrinsic(I, ISD::MEMMOVE);
1948 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001949
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001950 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001951 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001952 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001953 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001954 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00001955
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001956 Ops[0] = getRoot();
1957 Ops[1] = getValue(SPI.getLineValue());
1958 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00001959
Jim Laskeya8bdac82006-03-23 18:06:46 +00001960 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001961 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001962 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1963
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001964 Ops[3] = DAG.getString(CompileUnit->getFileName());
1965 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00001966
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001967 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001968 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001969
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001970 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001971 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001972 case Intrinsic::dbg_region_start: {
1973 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1974 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001975 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001976 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001977 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1978 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001979 }
1980
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001981 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001982 }
1983 case Intrinsic::dbg_region_end: {
1984 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1985 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001986 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001987 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001988 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1989 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001990 }
1991
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001992 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001993 }
1994 case Intrinsic::dbg_func_start: {
1995 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1996 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001997 if (DebugInfo && FSI.getSubprogram() &&
1998 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001999 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002000 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
2001 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00002002 }
2003
Chris Lattnerf2b62f32005-11-16 07:22:30 +00002004 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00002005 }
2006 case Intrinsic::dbg_declare: {
2007 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2008 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey67a636c2006-03-28 13:45:20 +00002009 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00002010 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002011 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeya8bdac82006-03-23 18:06:46 +00002012 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00002013 }
2014
2015 return 0;
2016 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002017
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002018 case Intrinsic::sqrt_f32:
2019 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002020 setValue(&I, DAG.getNode(ISD::FSQRT,
2021 getValue(I.getOperand(1)).getValueType(),
2022 getValue(I.getOperand(1))));
2023 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00002024 case Intrinsic::powi_f32:
2025 case Intrinsic::powi_f64:
2026 setValue(&I, DAG.getNode(ISD::FPOWI,
2027 getValue(I.getOperand(1)).getValueType(),
2028 getValue(I.getOperand(1)),
2029 getValue(I.getOperand(2))));
2030 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002031 case Intrinsic::pcmarker: {
2032 SDOperand Tmp = getValue(I.getOperand(1));
2033 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2034 return 0;
2035 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002036 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002037 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002038 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2039 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2040 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002041 setValue(&I, Tmp);
2042 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00002043 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00002044 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00002045 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002046 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00002047 case Intrinsic::bswap_i64:
2048 setValue(&I, DAG.getNode(ISD::BSWAP,
2049 getValue(I.getOperand(1)).getValueType(),
2050 getValue(I.getOperand(1))));
2051 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002052 case Intrinsic::cttz_i8:
2053 case Intrinsic::cttz_i16:
2054 case Intrinsic::cttz_i32:
2055 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002056 setValue(&I, DAG.getNode(ISD::CTTZ,
2057 getValue(I.getOperand(1)).getValueType(),
2058 getValue(I.getOperand(1))));
2059 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002060 case Intrinsic::ctlz_i8:
2061 case Intrinsic::ctlz_i16:
2062 case Intrinsic::ctlz_i32:
2063 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002064 setValue(&I, DAG.getNode(ISD::CTLZ,
2065 getValue(I.getOperand(1)).getValueType(),
2066 getValue(I.getOperand(1))));
2067 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00002068 case Intrinsic::ctpop_i8:
2069 case Intrinsic::ctpop_i16:
2070 case Intrinsic::ctpop_i32:
2071 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002072 setValue(&I, DAG.getNode(ISD::CTPOP,
2073 getValue(I.getOperand(1)).getValueType(),
2074 getValue(I.getOperand(1))));
2075 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00002076 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002077 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00002078 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2079 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00002080 setValue(&I, Tmp);
2081 DAG.setRoot(Tmp.getValue(1));
2082 return 0;
2083 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002084 case Intrinsic::stackrestore: {
2085 SDOperand Tmp = getValue(I.getOperand(1));
2086 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00002087 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00002088 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00002089 case Intrinsic::prefetch:
2090 // FIXME: Currently discarding prefetches.
2091 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002092 }
2093}
2094
2095
Chris Lattner7a60d912005-01-07 07:47:53 +00002096void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00002097 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002098 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00002099 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002100 if (unsigned IID = F->getIntrinsicID()) {
2101 RenameFn = visitIntrinsicCall(I, IID);
2102 if (!RenameFn)
2103 return;
2104 } else { // Not an LLVM intrinsic.
2105 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00002106 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2107 if (I.getNumOperands() == 3 && // Basic sanity checks.
2108 I.getOperand(1)->getType()->isFloatingPoint() &&
2109 I.getType() == I.getOperand(1)->getType() &&
2110 I.getType() == I.getOperand(2)->getType()) {
2111 SDOperand LHS = getValue(I.getOperand(1));
2112 SDOperand RHS = getValue(I.getOperand(2));
2113 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2114 LHS, RHS));
2115 return;
2116 }
2117 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00002118 if (I.getNumOperands() == 2 && // Basic sanity checks.
2119 I.getOperand(1)->getType()->isFloatingPoint() &&
2120 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002121 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00002122 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2123 return;
2124 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002125 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002126 if (I.getNumOperands() == 2 && // Basic sanity checks.
2127 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002128 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002129 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002130 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2131 return;
2132 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002133 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00002134 if (I.getNumOperands() == 2 && // Basic sanity checks.
2135 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00002136 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002137 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00002138 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2139 return;
2140 }
2141 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00002142 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002143 } else if (isa<InlineAsm>(I.getOperand(0))) {
2144 visitInlineAsm(I);
2145 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002146 }
Misha Brukman835702a2005-04-21 22:36:52 +00002147
Reid Spencere63b6512006-12-31 05:55:36 +00002148 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2149 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2150
Chris Lattner18d2b342005-01-08 22:48:57 +00002151 SDOperand Callee;
2152 if (!RenameFn)
2153 Callee = getValue(I.getOperand(0));
2154 else
2155 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Reid Spencere63b6512006-12-31 05:55:36 +00002156 TargetLowering::ArgListTy Args;
2157 TargetLowering::ArgListEntry Entry;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002158 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00002159 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2160 Value *Arg = I.getOperand(i);
2161 SDOperand ArgNode = getValue(Arg);
Reid Spencere63b6512006-12-31 05:55:36 +00002162 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2163 Entry.isSigned = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
2164 Args.push_back(Entry);
Chris Lattner7a60d912005-01-07 07:47:53 +00002165 }
Misha Brukman835702a2005-04-21 22:36:52 +00002166
Chris Lattner1f45cd72005-01-08 19:26:18 +00002167 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00002168 TLI.LowerCallTo(getRoot(), I.getType(),
2169 FTy->paramHasAttr(0,FunctionType::SExtAttribute),
2170 FTy->isVarArg(), I.getCallingConv(), I.isTailCall(),
2171 Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00002172 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00002173 setValue(&I, Result.first);
2174 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002175}
2176
Chris Lattner6f87d182006-02-22 22:37:12 +00002177SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002178 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00002179 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2180 Chain = Val.getValue(1);
2181 Flag = Val.getValue(2);
2182
2183 // If the result was expanded, copy from the top part.
2184 if (Regs.size() > 1) {
2185 assert(Regs.size() == 2 &&
2186 "Cannot expand to more than 2 elts yet!");
2187 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00002188 Chain = Hi.getValue(1);
2189 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002190 if (DAG.getTargetLoweringInfo().isLittleEndian())
2191 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2192 else
2193 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00002194 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002195
Chris Lattner705948d2006-06-08 18:22:48 +00002196 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00002197 // appropriate type.
2198 if (RegVT == ValueVT)
2199 return Val;
2200
Chris Lattner705948d2006-06-08 18:22:48 +00002201 if (MVT::isInteger(RegVT)) {
2202 if (ValueVT < RegVT)
2203 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2204 else
2205 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2206 } else {
Chris Lattner6f87d182006-02-22 22:37:12 +00002207 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00002208 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002209}
2210
Chris Lattner571d9642006-02-23 19:21:04 +00002211/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2212/// specified value into the registers specified by this object. This uses
2213/// Chain/Flag as the input and updates them for the output Chain/Flag.
2214void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00002215 SDOperand &Chain, SDOperand &Flag,
2216 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002217 if (Regs.size() == 1) {
2218 // If there is a single register and the types differ, this must be
2219 // a promotion.
2220 if (RegVT != ValueVT) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00002221 if (MVT::isInteger(RegVT)) {
2222 if (RegVT < ValueVT)
2223 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2224 else
2225 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2226 } else
Chris Lattner571d9642006-02-23 19:21:04 +00002227 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2228 }
2229 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2230 Flag = Chain.getValue(1);
2231 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002232 std::vector<unsigned> R(Regs);
2233 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2234 std::reverse(R.begin(), R.end());
2235
2236 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00002237 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00002238 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002239 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00002240 Flag = Chain.getValue(1);
2241 }
2242 }
2243}
Chris Lattner6f87d182006-02-22 22:37:12 +00002244
Chris Lattner571d9642006-02-23 19:21:04 +00002245/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2246/// operand list. This adds the code marker and includes the number of
2247/// values added into it.
2248void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00002249 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00002250 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2251 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2252 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2253}
Chris Lattner6f87d182006-02-22 22:37:12 +00002254
2255/// isAllocatableRegister - If the specified register is safe to allocate,
2256/// i.e. it isn't a stack pointer or some other special register, return the
2257/// register class for the register. Otherwise, return null.
2258static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00002259isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2260 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002261 MVT::ValueType FoundVT = MVT::Other;
2262 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002263 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2264 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002265 MVT::ValueType ThisVT = MVT::Other;
2266
Chris Lattnerb1124f32006-02-22 23:09:03 +00002267 const TargetRegisterClass *RC = *RCI;
2268 // If none of the the value types for this register class are valid, we
2269 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002270 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2271 I != E; ++I) {
2272 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00002273 // If we have already found this register in a different register class,
2274 // choose the one with the largest VT specified. For example, on
2275 // PowerPC, we favor f64 register classes over f32.
2276 if (FoundVT == MVT::Other ||
2277 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2278 ThisVT = *I;
2279 break;
2280 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00002281 }
2282 }
2283
Chris Lattnerbec582f2006-04-02 00:24:45 +00002284 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00002285
Chris Lattner6f87d182006-02-22 22:37:12 +00002286 // NOTE: This isn't ideal. In particular, this might allocate the
2287 // frame pointer in functions that need it (due to them not being taken
2288 // out of allocation, because a variable sized allocation hasn't been seen
2289 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00002290 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2291 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00002292 if (*I == Reg) {
2293 // We found a matching register class. Keep looking at others in case
2294 // we find one with larger registers that this physreg is also in.
2295 FoundRC = RC;
2296 FoundVT = ThisVT;
2297 break;
2298 }
Chris Lattner1558fc62006-02-01 18:59:47 +00002299 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00002300 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00002301}
2302
2303RegsForValue SelectionDAGLowering::
2304GetRegistersForValue(const std::string &ConstrCode,
2305 MVT::ValueType VT, bool isOutReg, bool isInReg,
2306 std::set<unsigned> &OutputRegs,
2307 std::set<unsigned> &InputRegs) {
2308 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2309 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2310 std::vector<unsigned> Regs;
2311
2312 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2313 MVT::ValueType RegVT;
2314 MVT::ValueType ValueVT = VT;
2315
Chris Lattner55402d42006-11-02 01:41:49 +00002316 // If this is a constraint for a specific physical register, like {r17},
2317 // assign it now.
Chris Lattner6f87d182006-02-22 22:37:12 +00002318 if (PhysReg.first) {
2319 if (VT == MVT::Other)
2320 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00002321
2322 // Get the actual register value type. This is important, because the user
2323 // may have asked for (e.g.) the AX register in i32 type. We need to
2324 // remember that AX is actually i16 to get the right extension.
2325 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00002326
2327 // This is a explicit reference to a physical register.
2328 Regs.push_back(PhysReg.first);
2329
2330 // If this is an expanded reference, add the rest of the regs to Regs.
2331 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002332 TargetRegisterClass::iterator I = PhysReg.second->begin();
2333 TargetRegisterClass::iterator E = PhysReg.second->end();
2334 for (; *I != PhysReg.first; ++I)
2335 assert(I != E && "Didn't find reg!");
2336
2337 // Already added the first reg.
2338 --NumRegs; ++I;
2339 for (; NumRegs; --NumRegs, ++I) {
2340 assert(I != E && "Ran out of registers to allocate!");
2341 Regs.push_back(*I);
2342 }
2343 }
2344 return RegsForValue(Regs, RegVT, ValueVT);
2345 }
2346
Chris Lattner55402d42006-11-02 01:41:49 +00002347 // Otherwise, if this was a reference to an LLVM register class, create vregs
2348 // for this reference.
2349 std::vector<unsigned> RegClassRegs;
2350 if (PhysReg.second) {
2351 // If this is an early clobber or tied register, our regalloc doesn't know
2352 // how to maintain the constraint. If it isn't, go ahead and create vreg
2353 // and let the regalloc do the right thing.
2354 if (!isOutReg || !isInReg) {
2355 if (VT == MVT::Other)
2356 ValueVT = *PhysReg.second->vt_begin();
2357 RegVT = *PhysReg.second->vt_begin();
2358
2359 // Create the appropriate number of virtual registers.
2360 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2361 for (; NumRegs; --NumRegs)
2362 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2363
2364 return RegsForValue(Regs, RegVT, ValueVT);
2365 }
2366
2367 // Otherwise, we can't allocate it. Let the code below figure out how to
2368 // maintain these constraints.
2369 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2370
2371 } else {
2372 // This is a reference to a register class that doesn't directly correspond
2373 // to an LLVM register class. Allocate NumRegs consecutive, available,
2374 // registers from the class.
2375 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2376 }
Chris Lattner6f87d182006-02-22 22:37:12 +00002377
2378 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2379 MachineFunction &MF = *CurMBB->getParent();
2380 unsigned NumAllocated = 0;
2381 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2382 unsigned Reg = RegClassRegs[i];
2383 // See if this register is available.
2384 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2385 (isInReg && InputRegs.count(Reg))) { // Already used.
2386 // Make sure we find consecutive registers.
2387 NumAllocated = 0;
2388 continue;
2389 }
2390
2391 // Check to see if this register is allocatable (i.e. don't give out the
2392 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00002393 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00002394 if (!RC) {
2395 // Make sure we find consecutive registers.
2396 NumAllocated = 0;
2397 continue;
2398 }
2399
2400 // Okay, this register is good, we can use it.
2401 ++NumAllocated;
2402
2403 // If we allocated enough consecutive
2404 if (NumAllocated == NumRegs) {
2405 unsigned RegStart = (i-NumAllocated)+1;
2406 unsigned RegEnd = i+1;
2407 // Mark all of the allocated registers used.
2408 for (unsigned i = RegStart; i != RegEnd; ++i) {
2409 unsigned Reg = RegClassRegs[i];
2410 Regs.push_back(Reg);
2411 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2412 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2413 }
2414
2415 return RegsForValue(Regs, *RC->vt_begin(), VT);
2416 }
2417 }
2418
2419 // Otherwise, we couldn't allocate enough registers for this.
2420 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00002421}
2422
Chris Lattner6f87d182006-02-22 22:37:12 +00002423
Chris Lattner476e67b2006-01-26 22:24:51 +00002424/// visitInlineAsm - Handle a call to an InlineAsm object.
2425///
2426void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2427 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2428
2429 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2430 MVT::Other);
2431
Chris Lattner3a5ed552006-02-01 01:28:23 +00002432 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002433 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002434
2435 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2436 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2437 /// if it is a def of that register.
2438 std::vector<SDOperand> AsmNodeOperands;
2439 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2440 AsmNodeOperands.push_back(AsmStr);
2441
2442 SDOperand Chain = getRoot();
2443 SDOperand Flag;
2444
Chris Lattner1558fc62006-02-01 18:59:47 +00002445 // We fully assign registers here at isel time. This is not optimal, but
2446 // should work. For register classes that correspond to LLVM classes, we
2447 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2448 // over the constraints, collecting fixed registers that we know we can't use.
2449 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002450 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002451 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2452 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2453 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00002454
Chris Lattner7ad77df2006-02-22 00:56:39 +00002455 MVT::ValueType OpVT;
2456
2457 // Compute the value type for each operand and add it to ConstraintVTs.
2458 switch (Constraints[i].Type) {
2459 case InlineAsm::isOutput:
2460 if (!Constraints[i].isIndirectOutput) {
2461 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2462 OpVT = TLI.getValueType(I.getType());
2463 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002464 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002465 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2466 OpNum++; // Consumes a call operand.
2467 }
2468 break;
2469 case InlineAsm::isInput:
2470 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2471 OpNum++; // Consumes a call operand.
2472 break;
2473 case InlineAsm::isClobber:
2474 OpVT = MVT::Other;
2475 break;
2476 }
2477
2478 ConstraintVTs.push_back(OpVT);
2479
Chris Lattner6f87d182006-02-22 22:37:12 +00002480 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2481 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002482
Chris Lattner6f87d182006-02-22 22:37:12 +00002483 // Build a list of regs that this operand uses. This always has a single
2484 // element for promoted/expanded operands.
2485 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2486 false, false,
2487 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002488
2489 switch (Constraints[i].Type) {
2490 case InlineAsm::isOutput:
2491 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002492 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002493 // If this is an early-clobber output, it cannot be assigned to the same
2494 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002495 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002496 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002497 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002498 case InlineAsm::isInput:
2499 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002500 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002501 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002502 case InlineAsm::isClobber:
2503 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002504 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2505 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002506 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002507 }
2508 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002509
Chris Lattner5c79f982006-02-21 23:12:12 +00002510 // Loop over all of the inputs, copying the operand values into the
2511 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002512 RegsForValue RetValRegs;
2513 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002514 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002515
Chris Lattner2e56e892006-01-31 02:03:41 +00002516 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00002517 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2518 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00002519
Chris Lattner3a5ed552006-02-01 01:28:23 +00002520 switch (Constraints[i].Type) {
2521 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002522 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2523 if (ConstraintCode.size() == 1) // not a physreg name.
2524 CTy = TLI.getConstraintType(ConstraintCode[0]);
2525
2526 if (CTy == TargetLowering::C_Memory) {
2527 // Memory output.
2528 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2529
2530 // Check that the operand (the address to store to) isn't a float.
2531 if (!MVT::isInteger(InOperandVal.getValueType()))
2532 assert(0 && "MATCH FAIL!");
2533
2534 if (!Constraints[i].isIndirectOutput)
2535 assert(0 && "MATCH FAIL!");
2536
2537 OpNum++; // Consumes a call operand.
2538
2539 // Extend/truncate to the right pointer type if needed.
2540 MVT::ValueType PtrType = TLI.getPointerTy();
2541 if (InOperandVal.getValueType() < PtrType)
2542 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2543 else if (InOperandVal.getValueType() > PtrType)
2544 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2545
2546 // Add information to the INLINEASM node to know about this output.
2547 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2548 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2549 AsmNodeOperands.push_back(InOperandVal);
2550 break;
2551 }
2552
2553 // Otherwise, this is a register output.
2554 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2555
Chris Lattner6f87d182006-02-22 22:37:12 +00002556 // If this is an early-clobber output, or if there is an input
2557 // constraint that matches this, we need to reserve the input register
2558 // so no other inputs allocate to it.
2559 bool UsesInputRegister = false;
2560 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2561 UsesInputRegister = true;
2562
2563 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002564 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002565 RegsForValue Regs =
2566 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2567 true, UsesInputRegister,
2568 OutputRegs, InputRegs);
Chris Lattner968f8032006-10-31 07:33:13 +00002569 if (Regs.Regs.empty()) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002570 cerr << "Couldn't allocate output reg for contraint '"
2571 << ConstraintCode << "'!\n";
Chris Lattner968f8032006-10-31 07:33:13 +00002572 exit(1);
2573 }
Chris Lattner7ad77df2006-02-22 00:56:39 +00002574
Chris Lattner3a5ed552006-02-01 01:28:23 +00002575 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002576 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002577 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002578 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002579 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002580 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002581 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2582 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002583 OpNum++; // Consumes a call operand.
2584 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002585
2586 // Add information to the INLINEASM node to know that this register is
2587 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002588 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002589 break;
2590 }
2591 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002592 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002593 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002594
Chris Lattner7f5880b2006-02-02 00:25:23 +00002595 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2596 // If this is required to match an output register we have already set,
2597 // just use its register.
2598 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002599
Chris Lattner571d9642006-02-23 19:21:04 +00002600 // Scan until we find the definition we already emitted of this operand.
2601 // When we find it, create a RegsForValue operand.
2602 unsigned CurOp = 2; // The first operand.
2603 for (; OperandNo; --OperandNo) {
2604 // Advance to the next operand.
2605 unsigned NumOps =
2606 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00002607 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2608 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00002609 "Skipped past definitions?");
2610 CurOp += (NumOps>>3)+1;
2611 }
2612
2613 unsigned NumOps =
2614 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2615 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2616 "Skipped past definitions?");
2617
2618 // Add NumOps>>3 registers to MatchedRegs.
2619 RegsForValue MatchedRegs;
2620 MatchedRegs.ValueVT = InOperandVal.getValueType();
2621 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2622 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2623 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2624 MatchedRegs.Regs.push_back(Reg);
2625 }
2626
2627 // Use the produced MatchedRegs object to
Evan Chengef9e07d2006-06-15 08:11:54 +00002628 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2629 TLI.getPointerTy());
Chris Lattner571d9642006-02-23 19:21:04 +00002630 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00002631 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00002632 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002633
2634 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2635 if (ConstraintCode.size() == 1) // not a physreg name.
2636 CTy = TLI.getConstraintType(ConstraintCode[0]);
2637
2638 if (CTy == TargetLowering::C_Other) {
Chris Lattner6f043b92006-10-31 19:41:18 +00002639 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2640 ConstraintCode[0], DAG);
2641 if (!InOperandVal.Val) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002642 cerr << "Invalid operand for inline asm constraint '"
2643 << ConstraintCode << "'!\n";
Chris Lattner6f043b92006-10-31 19:41:18 +00002644 exit(1);
2645 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002646
2647 // Add information to the INLINEASM node to know about this input.
2648 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2649 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2650 AsmNodeOperands.push_back(InOperandVal);
2651 break;
2652 } else if (CTy == TargetLowering::C_Memory) {
2653 // Memory input.
2654
2655 // Check that the operand isn't a float.
2656 if (!MVT::isInteger(InOperandVal.getValueType()))
2657 assert(0 && "MATCH FAIL!");
2658
2659 // Extend/truncate to the right pointer type if needed.
2660 MVT::ValueType PtrType = TLI.getPointerTy();
2661 if (InOperandVal.getValueType() < PtrType)
2662 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2663 else if (InOperandVal.getValueType() > PtrType)
2664 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2665
2666 // Add information to the INLINEASM node to know about this input.
2667 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2668 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2669 AsmNodeOperands.push_back(InOperandVal);
2670 break;
2671 }
2672
2673 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2674
2675 // Copy the input into the appropriate registers.
2676 RegsForValue InRegs =
2677 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2678 false, true, OutputRegs, InputRegs);
2679 // FIXME: should be match fail.
2680 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2681
Evan Chengef9e07d2006-06-15 08:11:54 +00002682 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00002683
2684 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002685 break;
2686 }
Chris Lattner571d9642006-02-23 19:21:04 +00002687 case InlineAsm::isClobber: {
2688 RegsForValue ClobberedRegs =
2689 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2690 OutputRegs, InputRegs);
2691 // Add the clobbered value to the operand list, so that the register
2692 // allocator is aware that the physreg got clobbered.
2693 if (!ClobberedRegs.Regs.empty())
2694 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002695 break;
2696 }
Chris Lattner571d9642006-02-23 19:21:04 +00002697 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002698 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002699
2700 // Finish up input operands.
2701 AsmNodeOperands[0] = Chain;
2702 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2703
Chris Lattnerbd887772006-08-14 23:53:35 +00002704 Chain = DAG.getNode(ISD::INLINEASM,
2705 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002706 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002707 Flag = Chain.getValue(1);
2708
Chris Lattner2e56e892006-01-31 02:03:41 +00002709 // If this asm returns a register value, copy the result from that register
2710 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002711 if (!RetValRegs.Regs.empty())
2712 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002713
Chris Lattner2e56e892006-01-31 02:03:41 +00002714 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2715
2716 // Process indirect outputs, first output all of the flagged copies out of
2717 // physregs.
2718 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002719 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002720 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002721 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2722 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002723 }
2724
2725 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002726 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00002727 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00002728 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00002729 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00002730 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00002731 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002732 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2733 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002734 DAG.setRoot(Chain);
2735}
2736
2737
Chris Lattner7a60d912005-01-07 07:47:53 +00002738void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2739 SDOperand Src = getValue(I.getOperand(0));
2740
2741 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002742
2743 if (IntPtr < Src.getValueType())
2744 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2745 else if (IntPtr > Src.getValueType())
2746 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002747
2748 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00002749 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00002750 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2751 Src, getIntPtrConstant(ElementSize));
2752
Reid Spencere63b6512006-12-31 05:55:36 +00002753 TargetLowering::ArgListTy Args;
2754 TargetLowering::ArgListEntry Entry;
2755 Entry.Node = Src;
2756 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2757 Entry.isSigned = false;
2758 Args.push_back(Entry);
Chris Lattner1f45cd72005-01-08 19:26:18 +00002759
2760 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00002761 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002762 DAG.getExternalSymbol("malloc", IntPtr),
2763 Args, DAG);
2764 setValue(&I, Result.first); // Pointers always fit in registers
2765 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002766}
2767
2768void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencere63b6512006-12-31 05:55:36 +00002769 TargetLowering::ArgListTy Args;
2770 TargetLowering::ArgListEntry Entry;
2771 Entry.Node = getValue(I.getOperand(0));
2772 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2773 Entry.isSigned = false;
2774 Args.push_back(Entry);
Chris Lattner7a60d912005-01-07 07:47:53 +00002775 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002776 std::pair<SDOperand,SDOperand> Result =
Reid Spencere63b6512006-12-31 05:55:36 +00002777 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002778 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2779 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002780}
2781
Chris Lattner13d7c252005-08-26 20:54:47 +00002782// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2783// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2784// instructions are special in various ways, which require special support to
2785// insert. The specified MachineInstr is created but not inserted into any
2786// basic blocks, and the scheduler passes ownership of it to this method.
2787MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2788 MachineBasicBlock *MBB) {
Bill Wendling22e978a2006-12-07 20:04:42 +00002789 cerr << "If a target marks an instruction with "
2790 << "'usesCustomDAGSchedInserter', it must implement "
2791 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner13d7c252005-08-26 20:54:47 +00002792 abort();
2793 return 0;
2794}
2795
Chris Lattner58cfd792005-01-09 00:00:49 +00002796void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002797 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2798 getValue(I.getOperand(1)),
2799 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00002800}
2801
2802void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002803 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2804 getValue(I.getOperand(0)),
2805 DAG.getSrcValue(I.getOperand(0)));
2806 setValue(&I, V);
2807 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002808}
2809
2810void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002811 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2812 getValue(I.getOperand(1)),
2813 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002814}
2815
2816void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002817 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2818 getValue(I.getOperand(1)),
2819 getValue(I.getOperand(2)),
2820 DAG.getSrcValue(I.getOperand(1)),
2821 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002822}
2823
Evan Cheng0c0b78c2006-12-12 07:27:38 +00002824/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
2825/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
2826static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
2827 unsigned &i, SelectionDAG &DAG,
2828 TargetLowering &TLI) {
2829 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
2830 return SDOperand(Arg, i++);
2831
2832 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
2833 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
2834 if (NumVals == 1) {
2835 return DAG.getNode(ISD::BIT_CONVERT, VT,
2836 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
2837 } else if (NumVals == 2) {
2838 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2839 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2840 if (!TLI.isLittleEndian())
2841 std::swap(Lo, Hi);
2842 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
2843 } else {
2844 // Value scalarized into many values. Unimp for now.
2845 assert(0 && "Cannot expand i64 -> i16 yet!");
2846 }
2847 return SDOperand();
2848}
2849
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002850/// TargetLowering::LowerArguments - This is the default LowerArguments
2851/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00002852/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2853/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002854std::vector<SDOperand>
2855TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2856 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2857 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00002858 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002859 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2860 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2861
2862 // Add one result value for each formal argument.
2863 std::vector<MVT::ValueType> RetVals;
2864 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2865 MVT::ValueType VT = getValueType(I->getType());
2866
2867 switch (getTypeAction(VT)) {
2868 default: assert(0 && "Unknown type action!");
2869 case Legal:
2870 RetVals.push_back(VT);
2871 break;
2872 case Promote:
2873 RetVals.push_back(getTypeToTransformTo(VT));
2874 break;
2875 case Expand:
2876 if (VT != MVT::Vector) {
2877 // If this is a large integer, it needs to be broken up into small
2878 // integers. Figure out what the destination type is and how many small
2879 // integers it turns into.
Evan Cheng22cf8992006-12-13 20:57:08 +00002880 MVT::ValueType NVT = getTypeToExpandTo(VT);
2881 unsigned NumVals = getNumElements(VT);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002882 for (unsigned i = 0; i != NumVals; ++i)
2883 RetVals.push_back(NVT);
2884 } else {
2885 // Otherwise, this is a vector type. We only support legal vectors
2886 // right now.
2887 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2888 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002889
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002890 // Figure out if there is a Packed type corresponding to this Vector
2891 // type. If so, convert to the packed type.
2892 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2893 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2894 RetVals.push_back(TVT);
2895 } else {
2896 assert(0 && "Don't support illegal by-val vector arguments yet!");
2897 }
2898 }
2899 break;
2900 }
2901 }
Evan Cheng9618df12006-04-25 23:03:35 +00002902
Chris Lattner3d826992006-05-16 06:45:34 +00002903 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002904
2905 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00002906 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2907 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002908 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00002909
2910 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002911
2912 // Set up the return result vector.
2913 Ops.clear();
Reid Spencere63b6512006-12-31 05:55:36 +00002914 const FunctionType *FTy = F.getFunctionType();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002915 unsigned i = 0;
Reid Spencere63b6512006-12-31 05:55:36 +00002916 unsigned Idx = 1;
2917 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
2918 ++I, ++Idx) {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002919 MVT::ValueType VT = getValueType(I->getType());
2920
2921 switch (getTypeAction(VT)) {
2922 default: assert(0 && "Unknown type action!");
2923 case Legal:
2924 Ops.push_back(SDOperand(Result, i++));
2925 break;
2926 case Promote: {
2927 SDOperand Op(Result, i++);
2928 if (MVT::isInteger(VT)) {
Chris Lattner96035be2007-01-04 22:22:37 +00002929 if (FTy->paramHasAttr(Idx, FunctionType::SExtAttribute))
2930 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
2931 DAG.getValueType(VT));
2932 else if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
2933 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
2934 DAG.getValueType(VT));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002935 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2936 } else {
2937 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2938 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2939 }
2940 Ops.push_back(Op);
2941 break;
2942 }
2943 case Expand:
2944 if (VT != MVT::Vector) {
Evan Cheng0c0b78c2006-12-12 07:27:38 +00002945 // If this is a large integer or a floating point node that needs to be
2946 // expanded, it needs to be reassembled from small integers. Figure out
2947 // what the source elt type is and how many small integers it is.
2948 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002949 } else {
2950 // Otherwise, this is a vector type. We only support legal vectors
2951 // right now.
Evan Chengd43c5c62006-04-28 05:25:15 +00002952 const PackedType *PTy = cast<PackedType>(I->getType());
2953 unsigned NumElems = PTy->getNumElements();
2954 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002955
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002956 // Figure out if there is a Packed type corresponding to this Vector
2957 // type. If so, convert to the packed type.
2958 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00002959 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00002960 SDOperand N = SDOperand(Result, i++);
2961 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00002962 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2963 DAG.getConstant(NumElems, MVT::i32),
2964 DAG.getValueType(getValueType(EltTy)));
2965 Ops.push_back(N);
2966 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002967 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00002968 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002969 }
2970 }
2971 break;
2972 }
2973 }
2974 return Ops;
2975}
2976
Chris Lattneraaa23d92006-05-16 22:53:20 +00002977
Evan Cheng0c0b78c2006-12-12 07:27:38 +00002978/// ExpandScalarCallArgs - Recursively expand call argument node by
2979/// bit_converting it or extract a pair of elements from the larger node.
2980static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
2981 bool isSigned,
2982 SmallVector<SDOperand, 32> &Ops,
2983 SelectionDAG &DAG,
2984 TargetLowering &TLI) {
2985 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
2986 Ops.push_back(Arg);
2987 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2988 return;
2989 }
2990
2991 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
2992 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
2993 if (NumVals == 1) {
2994 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
2995 ExpandScalarCallArgs(EVT, Arg, isSigned, Ops, DAG, TLI);
2996 } else if (NumVals == 2) {
2997 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
2998 DAG.getConstant(0, TLI.getPointerTy()));
2999 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3000 DAG.getConstant(1, TLI.getPointerTy()));
3001 if (!TLI.isLittleEndian())
3002 std::swap(Lo, Hi);
3003 ExpandScalarCallArgs(EVT, Lo, isSigned, Ops, DAG, TLI);
3004 ExpandScalarCallArgs(EVT, Hi, isSigned, Ops, DAG, TLI);
3005 } else {
3006 // Value scalarized into many values. Unimp for now.
3007 assert(0 && "Cannot expand i64 -> i16 yet!");
3008 }
3009}
3010
Chris Lattneraaa23d92006-05-16 22:53:20 +00003011/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3012/// implementation, which just inserts an ISD::CALL node, which is later custom
3013/// lowered by the target to something concrete. FIXME: When all targets are
3014/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3015std::pair<SDOperand, SDOperand>
Reid Spencere63b6512006-12-31 05:55:36 +00003016TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3017 bool RetTyIsSigned, bool isVarArg,
Chris Lattneraaa23d92006-05-16 22:53:20 +00003018 unsigned CallingConv, bool isTailCall,
3019 SDOperand Callee,
3020 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00003021 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003022 Ops.push_back(Chain); // Op#0 - Chain
3023 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3024 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3025 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3026 Ops.push_back(Callee);
3027
3028 // Handle all of the outgoing arguments.
3029 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencere63b6512006-12-31 05:55:36 +00003030 MVT::ValueType VT = getValueType(Args[i].Ty);
3031 SDOperand Op = Args[i].Node;
3032 bool isSigned = Args[i].isSigned;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003033 switch (getTypeAction(VT)) {
3034 default: assert(0 && "Unknown type action!");
3035 case Legal:
3036 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00003037 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003038 break;
3039 case Promote:
3040 if (MVT::isInteger(VT)) {
Evan Cheng45827712006-05-25 00:55:32 +00003041 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003042 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3043 } else {
3044 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3045 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3046 }
3047 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00003048 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00003049 break;
3050 case Expand:
3051 if (VT != MVT::Vector) {
3052 // If this is a large integer, it needs to be broken down into small
3053 // integers. Figure out what the source elt type is and how many small
3054 // integers it is.
Evan Cheng0c0b78c2006-12-12 07:27:38 +00003055 ExpandScalarCallArgs(VT, Op, isSigned, Ops, DAG, *this);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003056 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003057 // Otherwise, this is a vector type. We only support legal vectors
3058 // right now.
Reid Spencere63b6512006-12-31 05:55:36 +00003059 const PackedType *PTy = cast<PackedType>(Args[i].Ty);
Chris Lattnerb77ba732006-05-16 23:39:44 +00003060 unsigned NumElems = PTy->getNumElements();
3061 const Type *EltTy = PTy->getElementType();
3062
3063 // Figure out if there is a Packed type corresponding to this Vector
3064 // type. If so, convert to the packed type.
3065 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00003066 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3067 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
3068 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3069 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00003070 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00003071 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003072 assert(0 && "Don't support illegal by-val vector call args yet!");
3073 abort();
3074 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003075 }
3076 break;
3077 }
3078 }
3079
3080 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00003081 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003082
3083 if (RetTy != Type::VoidTy) {
3084 MVT::ValueType VT = getValueType(RetTy);
3085 switch (getTypeAction(VT)) {
3086 default: assert(0 && "Unknown type action!");
3087 case Legal:
3088 RetTys.push_back(VT);
3089 break;
3090 case Promote:
3091 RetTys.push_back(getTypeToTransformTo(VT));
3092 break;
3093 case Expand:
3094 if (VT != MVT::Vector) {
3095 // If this is a large integer, it needs to be reassembled from small
3096 // integers. Figure out what the source elt type is and how many small
3097 // integers it is.
Evan Cheng22cf8992006-12-13 20:57:08 +00003098 MVT::ValueType NVT = getTypeToExpandTo(VT);
3099 unsigned NumVals = getNumElements(VT);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003100 for (unsigned i = 0; i != NumVals; ++i)
3101 RetTys.push_back(NVT);
3102 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003103 // Otherwise, this is a vector type. We only support legal vectors
3104 // right now.
3105 const PackedType *PTy = cast<PackedType>(RetTy);
3106 unsigned NumElems = PTy->getNumElements();
3107 const Type *EltTy = PTy->getElementType();
3108
3109 // Figure out if there is a Packed type corresponding to this Vector
3110 // type. If so, convert to the packed type.
3111 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3112 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3113 RetTys.push_back(TVT);
3114 } else {
3115 assert(0 && "Don't support illegal by-val vector call results yet!");
3116 abort();
3117 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00003118 }
3119 }
3120 }
3121
3122 RetTys.push_back(MVT::Other); // Always has a chain.
3123
3124 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00003125 SDOperand Res = DAG.getNode(ISD::CALL,
3126 DAG.getVTList(&RetTys[0], RetTys.size()),
3127 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00003128
3129 // This returns a pair of operands. The first element is the
3130 // return value for the function (if RetTy is not VoidTy). The second
3131 // element is the outgoing token chain.
3132 SDOperand ResVal;
3133 if (RetTys.size() != 1) {
3134 MVT::ValueType VT = getValueType(RetTy);
3135 if (RetTys.size() == 2) {
3136 ResVal = Res;
3137
3138 // If this value was promoted, truncate it down.
3139 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003140 if (VT == MVT::Vector) {
3141 // Insert a VBITCONVERT to convert from the packed result type to the
3142 // MVT::Vector type.
3143 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3144 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3145
3146 // Figure out if there is a Packed type corresponding to this Vector
3147 // type. If so, convert to the packed type.
3148 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3149 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00003150 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3151 // "N x PTyElementVT" MVT::Vector type.
3152 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00003153 DAG.getConstant(NumElems, MVT::i32),
3154 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00003155 } else {
3156 abort();
3157 }
3158 } else if (MVT::isInteger(VT)) {
Reid Spencere63b6512006-12-31 05:55:36 +00003159 unsigned AssertOp = ISD::AssertSext;
3160 if (!RetTyIsSigned)
3161 AssertOp = ISD::AssertZext;
Chris Lattneraaa23d92006-05-16 22:53:20 +00003162 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3163 DAG.getValueType(VT));
3164 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3165 } else {
3166 assert(MVT::isFloatingPoint(VT));
Evan Cheng4eee7242006-12-09 02:42:38 +00003167 if (getTypeAction(VT) == Expand)
3168 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3169 else
3170 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattneraaa23d92006-05-16 22:53:20 +00003171 }
3172 }
3173 } else if (RetTys.size() == 3) {
3174 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3175 Res.getValue(0), Res.getValue(1));
3176
3177 } else {
3178 assert(0 && "Case not handled yet!");
3179 }
3180 }
3181
3182 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3183}
3184
3185
3186
Chris Lattner58cfd792005-01-09 00:00:49 +00003187// It is always conservatively correct for llvm.returnaddress and
3188// llvm.frameaddress to return 0.
Chris Lattneraaa23d92006-05-16 22:53:20 +00003189//
3190// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
3191// expanded to 0 if the target wants.
Chris Lattner58cfd792005-01-09 00:00:49 +00003192std::pair<SDOperand, SDOperand>
3193TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
3194 unsigned Depth, SelectionDAG &DAG) {
3195 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00003196}
3197
Chris Lattner29dcc712005-05-14 05:50:48 +00003198SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00003199 assert(0 && "LowerOperation not implemented for this target!");
3200 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00003201 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00003202}
3203
Nate Begeman595ec732006-01-28 03:14:31 +00003204SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3205 SelectionDAG &DAG) {
3206 assert(0 && "CustomPromoteOperation not implemented for this target!");
3207 abort();
3208 return SDOperand();
3209}
3210
Chris Lattner58cfd792005-01-09 00:00:49 +00003211void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003212 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner58cfd792005-01-09 00:00:49 +00003213 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00003214 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00003215 setValue(&I, Result.first);
3216 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00003217}
3218
Evan Cheng6781b6e2006-02-15 21:59:04 +00003219/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00003220/// operand.
3221static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00003222 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003223 MVT::ValueType CurVT = VT;
3224 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3225 uint64_t Val = C->getValue() & 255;
3226 unsigned Shift = 8;
3227 while (CurVT != MVT::i8) {
3228 Val = (Val << Shift) | Val;
3229 Shift <<= 1;
3230 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003231 }
3232 return DAG.getConstant(Val, VT);
3233 } else {
3234 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3235 unsigned Shift = 8;
3236 while (CurVT != MVT::i8) {
3237 Value =
3238 DAG.getNode(ISD::OR, VT,
3239 DAG.getNode(ISD::SHL, VT, Value,
3240 DAG.getConstant(Shift, MVT::i8)), Value);
3241 Shift <<= 1;
3242 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003243 }
3244
3245 return Value;
3246 }
3247}
3248
Evan Cheng6781b6e2006-02-15 21:59:04 +00003249/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3250/// used when a memcpy is turned into a memset when the source is a constant
3251/// string ptr.
3252static SDOperand getMemsetStringVal(MVT::ValueType VT,
3253 SelectionDAG &DAG, TargetLowering &TLI,
3254 std::string &Str, unsigned Offset) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003255 uint64_t Val = 0;
3256 unsigned MSB = getSizeInBits(VT) / 8;
3257 if (TLI.isLittleEndian())
3258 Offset = Offset + MSB - 1;
3259 for (unsigned i = 0; i != MSB; ++i) {
Evan Cheng6e12a052006-11-29 01:38:07 +00003260 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng6781b6e2006-02-15 21:59:04 +00003261 Offset += TLI.isLittleEndian() ? -1 : 1;
3262 }
3263 return DAG.getConstant(Val, VT);
3264}
3265
Evan Cheng81fcea82006-02-14 08:22:34 +00003266/// getMemBasePlusOffset - Returns base and offset node for the
3267static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3268 SelectionDAG &DAG, TargetLowering &TLI) {
3269 MVT::ValueType VT = Base.getValueType();
3270 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3271}
3272
Evan Chengdb2a7a72006-02-14 20:12:38 +00003273/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00003274/// to replace the memset / memcpy is below the threshold. It also returns the
3275/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00003276static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3277 unsigned Limit, uint64_t Size,
3278 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003279 MVT::ValueType VT;
3280
3281 if (TLI.allowsUnalignedMemoryAccesses()) {
3282 VT = MVT::i64;
3283 } else {
3284 switch (Align & 7) {
3285 case 0:
3286 VT = MVT::i64;
3287 break;
3288 case 4:
3289 VT = MVT::i32;
3290 break;
3291 case 2:
3292 VT = MVT::i16;
3293 break;
3294 default:
3295 VT = MVT::i8;
3296 break;
3297 }
3298 }
3299
Evan Chengd5026102006-02-14 09:11:59 +00003300 MVT::ValueType LVT = MVT::i64;
3301 while (!TLI.isTypeLegal(LVT))
3302 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3303 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00003304
Evan Chengd5026102006-02-14 09:11:59 +00003305 if (VT > LVT)
3306 VT = LVT;
3307
Evan Cheng04514992006-02-14 23:05:54 +00003308 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00003309 while (Size != 0) {
3310 unsigned VTSize = getSizeInBits(VT) / 8;
3311 while (VTSize > Size) {
3312 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00003313 VTSize >>= 1;
3314 }
Evan Chengd5026102006-02-14 09:11:59 +00003315 assert(MVT::isInteger(VT));
3316
3317 if (++NumMemOps > Limit)
3318 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00003319 MemOps.push_back(VT);
3320 Size -= VTSize;
3321 }
Evan Chengd5026102006-02-14 09:11:59 +00003322
3323 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00003324}
3325
Chris Lattner875def92005-01-11 05:56:49 +00003326void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00003327 SDOperand Op1 = getValue(I.getOperand(1));
3328 SDOperand Op2 = getValue(I.getOperand(2));
3329 SDOperand Op3 = getValue(I.getOperand(3));
3330 SDOperand Op4 = getValue(I.getOperand(4));
3331 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3332 if (Align == 0) Align = 1;
3333
3334 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3335 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00003336
3337 // Expand memset / memcpy to a series of load / store ops
3338 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003339 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00003340 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00003341 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00003342 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00003343 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3344 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00003345 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00003346 unsigned Offset = 0;
3347 for (unsigned i = 0; i < NumMemOps; i++) {
3348 MVT::ValueType VT = MemOps[i];
3349 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00003350 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00003351 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00003352 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003353 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00003354 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00003355 Offset += VTSize;
3356 }
Evan Cheng81fcea82006-02-14 08:22:34 +00003357 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003358 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00003359 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003360 case ISD::MEMCPY: {
3361 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3362 Size->getValue(), Align, TLI)) {
3363 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003364 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003365 GlobalAddressSDNode *G = NULL;
3366 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003367 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003368
3369 if (Op2.getOpcode() == ISD::GlobalAddress)
3370 G = cast<GlobalAddressSDNode>(Op2);
3371 else if (Op2.getOpcode() == ISD::ADD &&
3372 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3373 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3374 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003375 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00003376 }
3377 if (G) {
3378 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengfeba5072006-11-29 01:58:12 +00003379 if (GV && GV->isConstant()) {
Evan Cheng38280c02006-03-10 23:52:03 +00003380 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003381 if (!Str.empty()) {
3382 CopyFromStr = true;
3383 SrcOff += SrcDelta;
3384 }
3385 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00003386 }
3387
Evan Chenge2038bd2006-02-15 01:54:51 +00003388 for (unsigned i = 0; i < NumMemOps; i++) {
3389 MVT::ValueType VT = MemOps[i];
3390 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00003391 SDOperand Value, Chain, Store;
3392
Evan Chengc3dcf5a2006-02-16 23:11:42 +00003393 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00003394 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3395 Chain = getRoot();
3396 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003397 DAG.getStore(Chain, Value,
3398 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003399 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003400 } else {
3401 Value = DAG.getLoad(VT, getRoot(),
3402 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00003403 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003404 Chain = Value.getValue(1);
3405 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00003406 DAG.getStore(Chain, Value,
3407 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00003408 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003409 }
Evan Chenge2038bd2006-02-15 01:54:51 +00003410 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00003411 SrcOff += VTSize;
3412 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00003413 }
3414 }
3415 break;
3416 }
3417 }
3418
3419 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003420 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3421 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00003422 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00003423 }
3424 }
3425
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003426 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00003427}
3428
Chris Lattner875def92005-01-11 05:56:49 +00003429//===----------------------------------------------------------------------===//
3430// SelectionDAGISel code
3431//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00003432
3433unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3434 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3435}
3436
Chris Lattnerc9950c12005-08-17 06:37:43 +00003437void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00003438 // FIXME: we only modify the CFG to split critical edges. This
3439 // updates dom and loop info.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003440 AU.addRequired<AliasAnalysis>();
Chris Lattnerc9950c12005-08-17 06:37:43 +00003441}
Chris Lattner7a60d912005-01-07 07:47:53 +00003442
Chris Lattner35397782005-12-05 07:10:48 +00003443
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003444/// OptimizeNoopCopyExpression - We have determined that the specified cast
3445/// instruction is a noop copy (e.g. it's casting from one pointer type to
3446/// another, int->uint, or int->sbyte on PPC.
3447///
3448/// Return true if any changes are made.
3449static bool OptimizeNoopCopyExpression(CastInst *CI) {
3450 BasicBlock *DefBB = CI->getParent();
3451
3452 /// InsertedCasts - Only insert a cast in each block once.
3453 std::map<BasicBlock*, CastInst*> InsertedCasts;
3454
3455 bool MadeChange = false;
3456 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3457 UI != E; ) {
3458 Use &TheUse = UI.getUse();
3459 Instruction *User = cast<Instruction>(*UI);
3460
3461 // Figure out which BB this cast is used in. For PHI's this is the
3462 // appropriate predecessor block.
3463 BasicBlock *UserBB = User->getParent();
3464 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3465 unsigned OpVal = UI.getOperandNo()/2;
3466 UserBB = PN->getIncomingBlock(OpVal);
3467 }
3468
3469 // Preincrement use iterator so we don't invalidate it.
3470 ++UI;
3471
3472 // If this user is in the same block as the cast, don't change the cast.
3473 if (UserBB == DefBB) continue;
3474
3475 // If we have already inserted a cast into this block, use it.
3476 CastInst *&InsertedCast = InsertedCasts[UserBB];
3477
3478 if (!InsertedCast) {
3479 BasicBlock::iterator InsertPt = UserBB->begin();
3480 while (isa<PHINode>(InsertPt)) ++InsertPt;
3481
3482 InsertedCast =
Reid Spencerbfe26ff2006-12-13 00:50:17 +00003483 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
3484 InsertPt);
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003485 MadeChange = true;
3486 }
3487
3488 // Replace a use of the cast with a use of the new casat.
3489 TheUse = InsertedCast;
3490 }
3491
3492 // If we removed all uses, nuke the cast.
3493 if (CI->use_empty())
3494 CI->eraseFromParent();
3495
3496 return MadeChange;
3497}
3498
Chris Lattner35397782005-12-05 07:10:48 +00003499/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3500/// casting to the type of GEPI.
Chris Lattner21cd9902006-05-06 09:10:37 +00003501static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3502 Instruction *GEPI, Value *Ptr,
3503 Value *PtrOffset) {
Chris Lattner35397782005-12-05 07:10:48 +00003504 if (V) return V; // Already computed.
3505
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003506 // Figure out the insertion point
Chris Lattner35397782005-12-05 07:10:48 +00003507 BasicBlock::iterator InsertPt;
3508 if (BB == GEPI->getParent()) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003509 // If GEP is already inserted into BB, insert right after the GEP.
Chris Lattner35397782005-12-05 07:10:48 +00003510 InsertPt = GEPI;
3511 ++InsertPt;
3512 } else {
3513 // Otherwise, insert at the top of BB, after any PHI nodes
3514 InsertPt = BB->begin();
3515 while (isa<PHINode>(InsertPt)) ++InsertPt;
3516 }
3517
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003518 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3519 // BB so that there is only one value live across basic blocks (the cast
3520 // operand).
3521 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3522 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
Reid Spencerbfe26ff2006-12-13 00:50:17 +00003523 Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3524 "", InsertPt);
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003525
Chris Lattner35397782005-12-05 07:10:48 +00003526 // Add the offset, cast it to the right type.
3527 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003528 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3529 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3530 "", InsertPt);
Chris Lattner35397782005-12-05 07:10:48 +00003531}
3532
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003533/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3534/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3535/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3536/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3537/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3538/// the constant add into a load or store instruction. Additionally, if a user
3539/// is a pointer-pointer cast, we look through it to find its users.
3540static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3541 Constant *PtrOffset, BasicBlock *DefBB,
3542 GetElementPtrInst *GEPI,
Chris Lattner21cd9902006-05-06 09:10:37 +00003543 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003544 while (!RepPtr->use_empty()) {
3545 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003546
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003547 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3548 // used for a Pointer-Pointer cast.
3549 if (isa<BitCastInst>(User)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003550 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003551
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003552 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3553 // could invalidate an iterator.
3554 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3555 continue;
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003556 }
3557
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003558 // If this is a load of the pointer, or a store through the pointer, emit
3559 // the increment into the load/store block.
Chris Lattner21cd9902006-05-06 09:10:37 +00003560 Instruction *NewVal;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003561 if (isa<LoadInst>(User) ||
3562 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3563 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3564 User->getParent(), GEPI,
3565 Ptr, PtrOffset);
3566 } else {
3567 // If this use is not foldable into the addressing mode, use a version
3568 // emitted in the GEP block.
3569 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3570 Ptr, PtrOffset);
3571 }
3572
Chris Lattner21cd9902006-05-06 09:10:37 +00003573 if (GEPI->getType() != RepPtr->getType()) {
3574 BasicBlock::iterator IP = NewVal;
3575 ++IP;
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003576 // NewVal must be a GEP which must be pointer type, so BitCast
3577 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
Chris Lattner21cd9902006-05-06 09:10:37 +00003578 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003579 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003580 }
3581}
Chris Lattner35397782005-12-05 07:10:48 +00003582
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003583
Chris Lattner35397782005-12-05 07:10:48 +00003584/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3585/// selection, we want to be a bit careful about some things. In particular, if
3586/// we have a GEP instruction that is used in a different block than it is
3587/// defined, the addressing expression of the GEP cannot be folded into loads or
3588/// stores that use it. In this case, decompose the GEP and move constant
3589/// indices into blocks that use it.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003590static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Anderson20a631f2006-05-03 01:29:57 +00003591 const TargetData *TD) {
Chris Lattner35397782005-12-05 07:10:48 +00003592 // If this GEP is only used inside the block it is defined in, there is no
3593 // need to rewrite it.
3594 bool isUsedOutsideDefBB = false;
3595 BasicBlock *DefBB = GEPI->getParent();
3596 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3597 UI != E; ++UI) {
3598 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3599 isUsedOutsideDefBB = true;
3600 break;
3601 }
3602 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003603 if (!isUsedOutsideDefBB) return false;
Chris Lattner35397782005-12-05 07:10:48 +00003604
3605 // If this GEP has no non-zero constant indices, there is nothing we can do,
3606 // ignore it.
3607 bool hasConstantIndex = false;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003608 bool hasVariableIndex = false;
Chris Lattner35397782005-12-05 07:10:48 +00003609 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3610 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003611 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003612 if (CI->getZExtValue()) {
Chris Lattner35397782005-12-05 07:10:48 +00003613 hasConstantIndex = true;
3614 break;
3615 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003616 } else {
3617 hasVariableIndex = true;
3618 }
Chris Lattner35397782005-12-05 07:10:48 +00003619 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003620
3621 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3622 if (!hasConstantIndex && !hasVariableIndex) {
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003623 /// The GEP operand must be a pointer, so must its result -> BitCast
3624 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003625 GEPI->getName(), GEPI);
3626 GEPI->replaceAllUsesWith(NC);
3627 GEPI->eraseFromParent();
3628 return true;
3629 }
3630
Chris Lattnerf1a54c02005-12-11 09:05:13 +00003631 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003632 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3633 return false;
Chris Lattner35397782005-12-05 07:10:48 +00003634
3635 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3636 // constant offset (which we now know is non-zero) and deal with it later.
3637 uint64_t ConstantOffset = 0;
Owen Anderson20a631f2006-05-03 01:29:57 +00003638 const Type *UIntPtrTy = TD->getIntPtrType();
Reid Spencer6c38f0b2006-11-27 01:05:10 +00003639 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
Chris Lattner35397782005-12-05 07:10:48 +00003640 const Type *Ty = GEPI->getOperand(0)->getType();
3641
3642 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3643 E = GEPI->op_end(); OI != E; ++OI) {
3644 Value *Idx = *OI;
3645 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003646 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003647 if (Field)
Owen Anderson20a631f2006-05-03 01:29:57 +00003648 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner35397782005-12-05 07:10:48 +00003649 Ty = StTy->getElementType(Field);
3650 } else {
3651 Ty = cast<SequentialType>(Ty)->getElementType();
3652
3653 // Handle constant subscripts.
3654 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003655 if (CI->getZExtValue() == 0) continue;
Reid Spencere63b6512006-12-31 05:55:36 +00003656 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003657 continue;
3658 }
3659
3660 // Ptr = Ptr + Idx * ElementSize;
3661
3662 // Cast Idx to UIntPtrTy if needed.
Reid Spencerbfe26ff2006-12-13 00:50:17 +00003663 Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
Chris Lattner35397782005-12-05 07:10:48 +00003664
Owen Anderson20a631f2006-05-03 01:29:57 +00003665 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner35397782005-12-05 07:10:48 +00003666 // Mask off bits that should not be set.
3667 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003668 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattner35397782005-12-05 07:10:48 +00003669
3670 // Multiply by the element size and add to the base.
3671 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3672 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3673 }
3674 }
3675
3676 // Make sure that the offset fits in uintptr_t.
3677 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003678 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattner35397782005-12-05 07:10:48 +00003679
3680 // Okay, we have now emitted all of the variable index parts to the BB that
3681 // the GEP is defined in. Loop over all of the using instructions, inserting
3682 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003683 // instruction to use the newly computed value, making GEPI dead. When the
3684 // user is a load or store instruction address, we emit the add into the user
3685 // block, otherwise we use a canonical version right next to the gep (these
3686 // won't be foldable as addresses, so we might as well share the computation).
3687
Chris Lattner21cd9902006-05-06 09:10:37 +00003688 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003689 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner35397782005-12-05 07:10:48 +00003690
3691 // Finally, the GEP is dead, remove it.
3692 GEPI->eraseFromParent();
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003693
3694 return true;
Chris Lattner35397782005-12-05 07:10:48 +00003695}
3696
Chris Lattnerbba52192006-10-28 19:22:10 +00003697
3698/// SplitEdgeNicely - Split the critical edge from TI to it's specified
3699/// successor if it will improve codegen. We only do this if the successor has
3700/// phi nodes (otherwise critical edges are ok). If there is already another
3701/// predecessor of the succ that is empty (and thus has no phi nodes), use it
3702/// instead of introducing a new block.
3703static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3704 BasicBlock *TIBB = TI->getParent();
3705 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3706 assert(isa<PHINode>(Dest->begin()) &&
3707 "This should only be called if Dest has a PHI!");
3708
3709 /// TIPHIValues - This array is lazily computed to determine the values of
3710 /// PHIs in Dest that TI would provide.
3711 std::vector<Value*> TIPHIValues;
3712
3713 // Check to see if Dest has any blocks that can be used as a split edge for
3714 // this terminator.
3715 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3716 BasicBlock *Pred = *PI;
3717 // To be usable, the pred has to end with an uncond branch to the dest.
3718 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3719 if (!PredBr || !PredBr->isUnconditional() ||
3720 // Must be empty other than the branch.
3721 &Pred->front() != PredBr)
3722 continue;
3723
3724 // Finally, since we know that Dest has phi nodes in it, we have to make
3725 // sure that jumping to Pred will have the same affect as going to Dest in
3726 // terms of PHI values.
3727 PHINode *PN;
3728 unsigned PHINo = 0;
3729 bool FoundMatch = true;
3730 for (BasicBlock::iterator I = Dest->begin();
3731 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3732 if (PHINo == TIPHIValues.size())
3733 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3734
3735 // If the PHI entry doesn't work, we can't use this pred.
3736 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3737 FoundMatch = false;
3738 break;
3739 }
3740 }
3741
3742 // If we found a workable predecessor, change TI to branch to Succ.
3743 if (FoundMatch) {
3744 Dest->removePredecessor(TIBB);
3745 TI->setSuccessor(SuccNum, Pred);
3746 return;
3747 }
3748 }
3749
3750 SplitCriticalEdge(TI, SuccNum, P, true);
3751}
3752
3753
Chris Lattner7a60d912005-01-07 07:47:53 +00003754bool SelectionDAGISel::runOnFunction(Function &Fn) {
3755 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3756 RegMap = MF.getSSARegMap();
Bill Wendling22e978a2006-12-07 20:04:42 +00003757 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00003758
Chris Lattner3e6b1c62006-10-28 17:04:37 +00003759 // First, split all critical edges.
Chris Lattner35397782005-12-05 07:10:48 +00003760 //
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003761 // In this pass we also look for GEP and cast instructions that are used
3762 // across basic blocks and rewrite them to improve basic-block-at-a-time
3763 // selection.
3764 //
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003765 bool MadeChange = true;
3766 while (MadeChange) {
3767 MadeChange = false;
Chris Lattner1a908c82005-08-18 17:35:14 +00003768 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnerbba52192006-10-28 19:22:10 +00003769 // Split all critical edges where the dest block has a PHI.
Chris Lattner3e6b1c62006-10-28 17:04:37 +00003770 TerminatorInst *BBTI = BB->getTerminator();
3771 if (BBTI->getNumSuccessors() > 1) {
3772 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbba52192006-10-28 19:22:10 +00003773 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3774 isCriticalEdge(BBTI, i, true))
3775 SplitEdgeNicely(BBTI, i, this);
Chris Lattner3e6b1c62006-10-28 17:04:37 +00003776 }
3777
Chris Lattner35397782005-12-05 07:10:48 +00003778
Chris Lattnera9caf952006-09-28 06:17:10 +00003779 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003780 Instruction *I = BBI++;
Chris Lattner90f42382006-11-29 01:12:32 +00003781
3782 if (CallInst *CI = dyn_cast<CallInst>(I)) {
3783 // If we found an inline asm expession, and if the target knows how to
3784 // lower it to normal LLVM code, do so now.
3785 if (isa<InlineAsm>(CI->getCalledValue()))
3786 if (const TargetAsmInfo *TAI =
3787 TLI.getTargetMachine().getTargetAsmInfo()) {
3788 if (TAI->ExpandInlineAsm(CI))
3789 BBI = BB->begin();
3790 }
3791 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003792 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003793 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner84cc1f72006-09-13 06:02:42 +00003794 // If the source of the cast is a constant, then this should have
3795 // already been constant folded. The only reason NOT to constant fold
3796 // it is if something (e.g. LSR) was careful to place the constant
3797 // evaluation in a block other than then one that uses it (e.g. to hoist
3798 // the address of globals out of a loop). If this is the case, we don't
3799 // want to forward-subst the cast.
3800 if (isa<Constant>(CI->getOperand(0)))
3801 continue;
3802
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003803 // If this is a noop copy, sink it into user blocks to reduce the number
3804 // of virtual registers that must be created and coallesced.
3805 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3806 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3807
3808 // This is an fp<->int conversion?
3809 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3810 continue;
3811
3812 // If this is an extension, it will be a zero or sign extension, which
3813 // isn't a noop.
3814 if (SrcVT < DstVT) continue;
3815
3816 // If these values will be promoted, find out what they will be promoted
3817 // to. This helps us consider truncates on PPC as noop copies when they
3818 // are.
3819 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3820 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3821 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3822 DstVT = TLI.getTypeToTransformTo(DstVT);
3823
3824 // If, after promotion, these are the same types, this is a noop copy.
3825 if (SrcVT == DstVT)
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003826 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003827 }
3828 }
Chris Lattner1a908c82005-08-18 17:35:14 +00003829 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003830 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00003831
Chris Lattner7a60d912005-01-07 07:47:53 +00003832 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3833
3834 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3835 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00003836
Chris Lattner7a60d912005-01-07 07:47:53 +00003837 return true;
3838}
3839
Chris Lattnered0110b2006-10-27 21:36:01 +00003840SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3841 unsigned Reg) {
3842 SDOperand Op = getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00003843 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00003844 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00003845 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00003846
3847 // If this type is not legal, we must make sure to not create an invalid
3848 // register use.
3849 MVT::ValueType SrcVT = Op.getValueType();
3850 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattner33182322005-08-16 21:55:35 +00003851 if (SrcVT == DestVT) {
Chris Lattnered0110b2006-10-27 21:36:01 +00003852 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00003853 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00003854 // Handle copies from generic vectors to registers.
3855 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3856 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3857 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00003858
Chris Lattner5fe1f542006-03-31 02:06:56 +00003859 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3860 // MVT::Vector type.
3861 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3862 DAG.getConstant(NE, MVT::i32),
3863 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00003864
Chris Lattner5fe1f542006-03-31 02:06:56 +00003865 // Loop over all of the elements of the resultant vector,
3866 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3867 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003868 SmallVector<SDOperand, 8> OutChains;
Chris Lattnered0110b2006-10-27 21:36:01 +00003869 SDOperand Root = getRoot();
Chris Lattner5fe1f542006-03-31 02:06:56 +00003870 for (unsigned i = 0; i != NE; ++i) {
3871 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003872 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003873 if (PTyElementVT == PTyLegalElementVT) {
3874 // Elements are legal.
3875 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3876 } else if (PTyLegalElementVT > PTyElementVT) {
3877 // Elements are promoted.
3878 if (MVT::isFloatingPoint(PTyLegalElementVT))
3879 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3880 else
3881 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3882 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3883 } else {
3884 // Elements are expanded.
3885 // The src value is expanded into multiple registers.
3886 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003887 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003888 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003889 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003890 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3891 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3892 }
Chris Lattner672a42d2006-03-21 19:20:37 +00003893 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003894 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3895 &OutChains[0], OutChains.size());
Evan Cheng22cf8992006-12-13 20:57:08 +00003896 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattner33182322005-08-16 21:55:35 +00003897 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00003898 if (MVT::isFloatingPoint(SrcVT))
3899 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3900 else
Chris Lattnera66403d2005-09-02 00:19:37 +00003901 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnered0110b2006-10-27 21:36:01 +00003902 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner33182322005-08-16 21:55:35 +00003903 } else {
Evan Cheng22cf8992006-12-13 20:57:08 +00003904 DestVT = TLI.getTypeToExpandTo(SrcVT);
3905 unsigned NumVals = TLI.getNumElements(SrcVT);
3906 if (NumVals == 1)
3907 return DAG.getCopyToReg(getRoot(), Reg,
3908 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
3909 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattner33182322005-08-16 21:55:35 +00003910 // The src value is expanded into multiple registers.
3911 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003912 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003913 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003914 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnered0110b2006-10-27 21:36:01 +00003915 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattner33182322005-08-16 21:55:35 +00003916 return DAG.getCopyToReg(Op, Reg+1, Hi);
3917 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003918}
3919
Chris Lattner16f64df2005-01-17 17:15:02 +00003920void SelectionDAGISel::
3921LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3922 std::vector<SDOperand> &UnorderedChains) {
3923 // If this is the entry block, emit arguments.
3924 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003925 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00003926 SDOperand OldRoot = SDL.DAG.getRoot();
3927 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00003928
Chris Lattner6871b232005-10-30 19:42:35 +00003929 unsigned a = 0;
3930 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3931 AI != E; ++AI, ++a)
3932 if (!AI->use_empty()) {
3933 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00003934
Chris Lattner6871b232005-10-30 19:42:35 +00003935 // If this argument is live outside of the entry block, insert a copy from
3936 // whereever we got it to the vreg that other BB's will reference it as.
3937 if (FuncInfo.ValueMap.count(AI)) {
3938 SDOperand Copy =
Chris Lattnered0110b2006-10-27 21:36:01 +00003939 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattner6871b232005-10-30 19:42:35 +00003940 UnorderedChains.push_back(Copy);
3941 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003942 }
Chris Lattner6871b232005-10-30 19:42:35 +00003943
Chris Lattner6871b232005-10-30 19:42:35 +00003944 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00003945 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00003946 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00003947}
3948
Chris Lattner7a60d912005-01-07 07:47:53 +00003949void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3950 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00003951 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00003952 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00003953
3954 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00003955
Chris Lattner6871b232005-10-30 19:42:35 +00003956 // Lower any arguments needed in this block if this is the entry block.
3957 if (LLVMBB == &LLVMBB->getParent()->front())
3958 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00003959
3960 BB = FuncInfo.MBBMap[LLVMBB];
3961 SDL.setCurrentBasicBlock(BB);
3962
3963 // Lower all of the non-terminator instructions.
3964 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3965 I != E; ++I)
3966 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00003967
Chris Lattner7a60d912005-01-07 07:47:53 +00003968 // Ensure that all instructions which are used outside of their defining
3969 // blocks are available as virtual registers.
3970 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00003971 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00003972 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00003973 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00003974 UnorderedChains.push_back(
Chris Lattnered0110b2006-10-27 21:36:01 +00003975 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00003976 }
3977
3978 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3979 // ensure constants are generated when needed. Remember the virtual registers
3980 // that need to be added to the Machine PHI nodes as input. We cannot just
3981 // directly add them, because expansion might result in multiple MBB's for one
3982 // BB. As such, the start of the BB might correspond to a different MBB than
3983 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00003984 //
Chris Lattner84a03502006-10-27 23:50:33 +00003985 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner7a60d912005-01-07 07:47:53 +00003986
3987 // Emit constants only once even if used by multiple PHI nodes.
3988 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00003989
Chris Lattner84a03502006-10-27 23:50:33 +00003990 // Vector bool would be better, but vector<bool> is really slow.
3991 std::vector<unsigned char> SuccsHandled;
3992 if (TI->getNumSuccessors())
3993 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
3994
Chris Lattner7a60d912005-01-07 07:47:53 +00003995 // Check successor nodes PHI nodes that expect a constant to be available from
3996 // this block.
Chris Lattner7a60d912005-01-07 07:47:53 +00003997 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3998 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00003999 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner84a03502006-10-27 23:50:33 +00004000 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattner707339a52006-09-07 01:59:34 +00004001
Chris Lattner84a03502006-10-27 23:50:33 +00004002 // If this terminator has multiple identical successors (common for
4003 // switches), only handle each succ once.
4004 unsigned SuccMBBNo = SuccMBB->getNumber();
4005 if (SuccsHandled[SuccMBBNo]) continue;
4006 SuccsHandled[SuccMBBNo] = true;
4007
4008 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner7a60d912005-01-07 07:47:53 +00004009 PHINode *PN;
4010
4011 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4012 // nodes and Machine PHI nodes, but the incoming operands have not been
4013 // emitted yet.
4014 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner84a03502006-10-27 23:50:33 +00004015 (PN = dyn_cast<PHINode>(I)); ++I) {
4016 // Ignore dead phi's.
4017 if (PN->use_empty()) continue;
4018
4019 unsigned Reg;
4020 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner90f42382006-11-29 01:12:32 +00004021
Chris Lattner84a03502006-10-27 23:50:33 +00004022 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4023 unsigned &RegOut = ConstantsOut[C];
4024 if (RegOut == 0) {
4025 RegOut = FuncInfo.CreateRegForValue(C);
4026 UnorderedChains.push_back(
4027 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner7a60d912005-01-07 07:47:53 +00004028 }
Chris Lattner84a03502006-10-27 23:50:33 +00004029 Reg = RegOut;
4030 } else {
4031 Reg = FuncInfo.ValueMap[PHIOp];
4032 if (Reg == 0) {
4033 assert(isa<AllocaInst>(PHIOp) &&
4034 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4035 "Didn't codegen value into a register!??");
4036 Reg = FuncInfo.CreateRegForValue(PHIOp);
4037 UnorderedChains.push_back(
4038 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattnerba380352006-03-31 02:12:18 +00004039 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004040 }
Chris Lattner84a03502006-10-27 23:50:33 +00004041
4042 // Remember that this register needs to added to the machine PHI node as
4043 // the input for this MBB.
4044 MVT::ValueType VT = TLI.getValueType(PN->getType());
4045 unsigned NumElements;
4046 if (VT != MVT::Vector)
4047 NumElements = TLI.getNumElements(VT);
4048 else {
4049 MVT::ValueType VT1,VT2;
4050 NumElements =
4051 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
4052 VT1, VT2);
4053 }
4054 for (unsigned i = 0, e = NumElements; i != e; ++i)
4055 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4056 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004057 }
4058 ConstantsOut.clear();
4059
Chris Lattner718b5c22005-01-13 17:59:43 +00004060 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00004061 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00004062 SDOperand Root = SDL.getRoot();
4063 if (Root.getOpcode() != ISD::EntryToken) {
4064 unsigned i = 0, e = UnorderedChains.size();
4065 for (; i != e; ++i) {
4066 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4067 if (UnorderedChains[i].Val->getOperand(0) == Root)
4068 break; // Don't add the root if we already indirectly depend on it.
4069 }
4070
4071 if (i == e)
4072 UnorderedChains.push_back(Root);
4073 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00004074 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4075 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00004076 }
4077
Chris Lattner7a60d912005-01-07 07:47:53 +00004078 // Lower the terminator after the copies are emitted.
4079 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00004080
Nate Begemaned728c12006-03-27 01:32:24 +00004081 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004082 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00004083 SwitchCases.clear();
4084 SwitchCases = SDL.SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004085 JT = SDL.JT;
Nate Begemaned728c12006-03-27 01:32:24 +00004086
Chris Lattner4108bb02005-01-17 19:43:36 +00004087 // Make sure the root of the DAG is up-to-date.
4088 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00004089}
4090
Nate Begemaned728c12006-03-27 01:32:24 +00004091void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00004092 // Get alias analysis for load/store combining.
4093 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4094
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004095 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004096 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004097
Bill Wendling22e978a2006-12-07 20:04:42 +00004098 DOUT << "Lowered selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004099 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004100
Chris Lattner7a60d912005-01-07 07:47:53 +00004101 // Second step, hack on the DAG until it only uses operations and types that
4102 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00004103 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00004104
Bill Wendling22e978a2006-12-07 20:04:42 +00004105 DOUT << "Legalized selection DAG:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004106 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004107
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00004108 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00004109 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00004110
Evan Cheng739a6a42006-01-21 02:32:06 +00004111 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00004112
Chris Lattner5ca31d92005-03-30 01:10:47 +00004113 // Third, instruction select all of the operations to machine code, adding the
4114 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00004115 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00004116
Bill Wendling22e978a2006-12-07 20:04:42 +00004117 DOUT << "Selected machine code:\n";
Chris Lattner7a60d912005-01-07 07:47:53 +00004118 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00004119}
Chris Lattner7a60d912005-01-07 07:47:53 +00004120
Nate Begemaned728c12006-03-27 01:32:24 +00004121void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4122 FunctionLoweringInfo &FuncInfo) {
4123 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4124 {
4125 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4126 CurDAG = &DAG;
4127
4128 // First step, lower LLVM code to some DAG. This DAG may use operations and
4129 // types that are not supported by the target.
4130 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4131
4132 // Second step, emit the lowered DAG as machine code.
4133 CodeGenAndEmitDAG(DAG);
4134 }
4135
Chris Lattner5ca31d92005-03-30 01:10:47 +00004136 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00004137 // PHI nodes in successors.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004138 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemaned728c12006-03-27 01:32:24 +00004139 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4140 MachineInstr *PHI = PHINodesToUpdate[i].first;
4141 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4142 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004143 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00004144 PHI->addMachineBasicBlockOperand(BB);
4145 }
4146 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00004147 }
Nate Begemaned728c12006-03-27 01:32:24 +00004148
Nate Begeman866b4b42006-04-23 06:26:20 +00004149 // If the JumpTable record is filled in, then we need to emit a jump table.
4150 // Updating the PHI nodes is tricky in this case, since we need to determine
4151 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004152 if (JT.Reg) {
4153 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
4154 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4155 CurDAG = &SDAG;
4156 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman866b4b42006-04-23 06:26:20 +00004157 MachineBasicBlock *RangeBB = BB;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004158 // Set the current basic block to the mbb we wish to insert the code into
4159 BB = JT.MBB;
4160 SDL.setCurrentBasicBlock(BB);
4161 // Emit the code
4162 SDL.visitJumpTable(JT);
4163 SDAG.setRoot(SDL.getRoot());
4164 CodeGenAndEmitDAG(SDAG);
4165 // Update PHI Nodes
4166 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4167 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4168 MachineBasicBlock *PHIBB = PHI->getParent();
4169 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4170 "This is not a machine PHI node that we are updating!");
Nate Begemandf488392006-05-03 03:48:02 +00004171 if (PHIBB == JT.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004172 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004173 PHI->addMachineBasicBlockOperand(RangeBB);
4174 }
4175 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00004176 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00004177 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00004178 }
4179 }
4180 return;
4181 }
4182
Chris Lattner76a7bc82006-10-22 23:00:53 +00004183 // If the switch block involved a branch to one of the actual successors, we
4184 // need to update PHI nodes in that block.
4185 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4186 MachineInstr *PHI = PHINodesToUpdate[i].first;
4187 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4188 "This is not a machine PHI node that we are updating!");
4189 if (BB->isSuccessor(PHI->getParent())) {
4190 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4191 PHI->addMachineBasicBlockOperand(BB);
4192 }
4193 }
4194
Nate Begemaned728c12006-03-27 01:32:24 +00004195 // If we generated any switch lowering information, build and codegen any
4196 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00004197 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemaned728c12006-03-27 01:32:24 +00004198 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4199 CurDAG = &SDAG;
4200 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00004201
Nate Begemaned728c12006-03-27 01:32:24 +00004202 // Set the current basic block to the mbb we wish to insert the code into
4203 BB = SwitchCases[i].ThisBB;
4204 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00004205
Nate Begemaned728c12006-03-27 01:32:24 +00004206 // Emit the code
4207 SDL.visitSwitchCase(SwitchCases[i]);
4208 SDAG.setRoot(SDL.getRoot());
4209 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00004210
4211 // Handle any PHI nodes in successors of this chunk, as if we were coming
4212 // from the original BB before switch expansion. Note that PHI nodes can
4213 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4214 // handle them the right number of times.
Chris Lattner963ddad2006-10-24 17:57:59 +00004215 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattner707339a52006-09-07 01:59:34 +00004216 for (MachineBasicBlock::iterator Phi = BB->begin();
4217 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4218 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4219 for (unsigned pn = 0; ; ++pn) {
4220 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4221 if (PHINodesToUpdate[pn].first == Phi) {
4222 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4223 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4224 break;
4225 }
4226 }
Nate Begemaned728c12006-03-27 01:32:24 +00004227 }
Chris Lattner707339a52006-09-07 01:59:34 +00004228
4229 // Don't process RHS if same block as LHS.
Chris Lattner963ddad2006-10-24 17:57:59 +00004230 if (BB == SwitchCases[i].FalseBB)
4231 SwitchCases[i].FalseBB = 0;
Chris Lattner707339a52006-09-07 01:59:34 +00004232
4233 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner61bcf912006-10-24 18:07:37 +00004234 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner963ddad2006-10-24 17:57:59 +00004235 SwitchCases[i].FalseBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00004236 }
Chris Lattner963ddad2006-10-24 17:57:59 +00004237 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00004238 }
Chris Lattner7a60d912005-01-07 07:47:53 +00004239}
Evan Cheng739a6a42006-01-21 02:32:06 +00004240
Jim Laskey95eda5b2006-08-01 14:21:23 +00004241
Evan Cheng739a6a42006-01-21 02:32:06 +00004242//===----------------------------------------------------------------------===//
4243/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4244/// target node in the graph.
4245void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4246 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00004247
Jim Laskey29e635d2006-08-02 12:30:23 +00004248 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00004249
4250 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00004251 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00004252 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00004253 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00004254
Jim Laskey03593f72006-08-01 18:29:48 +00004255 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00004256 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00004257 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00004258}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004259
Chris Lattner47639db2006-03-06 00:22:00 +00004260
Jim Laskey03593f72006-08-01 18:29:48 +00004261HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4262 return new HazardRecognizer();
4263}
4264
Chris Lattner6df34962006-10-11 03:58:02 +00004265//===----------------------------------------------------------------------===//
4266// Helper functions used by the generated instruction selector.
4267//===----------------------------------------------------------------------===//
4268// Calls to these methods are generated by tblgen.
4269
4270/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4271/// the dag combiner simplified the 255, we still want to match. RHS is the
4272/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4273/// specified in the .td file (e.g. 255).
4274bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4275 int64_t DesiredMaskS) {
4276 uint64_t ActualMask = RHS->getValue();
4277 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4278
4279 // If the actual mask exactly matches, success!
4280 if (ActualMask == DesiredMask)
4281 return true;
4282
4283 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4284 if (ActualMask & ~DesiredMask)
4285 return false;
4286
4287 // Otherwise, the DAG Combiner may have proven that the value coming in is
4288 // either already zero or is not demanded. Check for known zero input bits.
4289 uint64_t NeededMask = DesiredMask & ~ActualMask;
4290 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4291 return true;
4292
4293 // TODO: check to see if missing bits are just not demanded.
4294
4295 // Otherwise, this pattern doesn't match.
4296 return false;
4297}
4298
4299/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4300/// the dag combiner simplified the 255, we still want to match. RHS is the
4301/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4302/// specified in the .td file (e.g. 255).
4303bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4304 int64_t DesiredMaskS) {
4305 uint64_t ActualMask = RHS->getValue();
4306 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4307
4308 // If the actual mask exactly matches, success!
4309 if (ActualMask == DesiredMask)
4310 return true;
4311
4312 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4313 if (ActualMask & ~DesiredMask)
4314 return false;
4315
4316 // Otherwise, the DAG Combiner may have proven that the value coming in is
4317 // either already zero or is not demanded. Check for known zero input bits.
4318 uint64_t NeededMask = DesiredMask & ~ActualMask;
4319
4320 uint64_t KnownZero, KnownOne;
4321 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4322
4323 // If all the missing bits in the or are already known to be set, match!
4324 if ((NeededMask & KnownOne) == NeededMask)
4325 return true;
4326
4327 // TODO: check to see if missing bits are just not demanded.
4328
4329 // Otherwise, this pattern doesn't match.
4330 return false;
4331}
4332
Jim Laskey03593f72006-08-01 18:29:48 +00004333
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004334/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4335/// by tblgen. Others should not call it.
4336void SelectionDAGISel::
4337SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4338 std::vector<SDOperand> InOps;
4339 std::swap(InOps, Ops);
4340
4341 Ops.push_back(InOps[0]); // input chain.
4342 Ops.push_back(InOps[1]); // input asm string.
4343
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004344 unsigned i = 2, e = InOps.size();
4345 if (InOps[e-1].getValueType() == MVT::Flag)
4346 --e; // Don't process a flag operand if it is here.
4347
4348 while (i != e) {
4349 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4350 if ((Flags & 7) != 4 /*MEM*/) {
4351 // Just skip over this operand, copying the operands verbatim.
4352 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4353 i += (Flags >> 3) + 1;
4354 } else {
4355 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4356 // Otherwise, this is a memory operand. Ask the target to select it.
4357 std::vector<SDOperand> SelOps;
4358 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling22e978a2006-12-07 20:04:42 +00004359 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004360 exit(1);
4361 }
4362
4363 // Add this to the output node.
Chris Lattner9bd5ed62006-12-16 21:14:48 +00004364 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4365 MVT::i32));
Chris Lattnerdcf785b2006-02-24 02:13:54 +00004366 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4367 i += 2;
4368 }
4369 }
4370
4371 // Add the flag input back if present.
4372 if (e != InOps.size())
4373 Ops.push_back(InOps.back());
4374}