blob: 570cac8e26136ea29c50e01af9e86c15456ef879 [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-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 Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000016#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000017#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000018#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000022#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Jim Laskeyb2efb852006-01-04 22:28:25 +000027#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman37efe672006-04-22 18:53:45 +000030#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000031#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000032#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000033#include "llvm/CodeGen/SelectionDAG.h"
34#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000035#include "llvm/Target/MRegisterInfo.h"
Chris Lattner3f7927c2006-11-29 01:12:32 +000036#include "llvm/Target/TargetAsmInfo.h"
Chris Lattner1c08c712005-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 Prus12472912006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000047#include <iostream>
Jeff Cohen7e881032006-02-24 02:52:40 +000048#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000049using namespace llvm;
50
Chris Lattnerda8abb02005-09-01 18:44:10 +000051#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000052static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000053ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
55static cl::opt<bool>
56ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000058#else
Chris Lattner5e46a192006-04-02 03:07:27 +000059static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000060#endif
61
Jim Laskeyeb577ba2006-08-02 12:30:23 +000062
63//===---------------------------------------------------------------------===//
64///
65/// RegisterScheduler class - Track the registration of instruction schedulers.
66///
67//===---------------------------------------------------------------------===//
68MachinePassRegistry RegisterScheduler::Registry;
69
70//===---------------------------------------------------------------------===//
71///
72/// ISHeuristic command line option for instruction schedulers.
73///
74//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000075namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000076 cl::opt<RegisterScheduler::FunctionPassCtor, false,
77 RegisterPassParser<RegisterScheduler> >
Jim Laskey13ec7022006-08-01 14:21:23 +000078 ISHeuristic("sched",
Chris Lattner3700f902006-08-03 00:18:59 +000079 cl::init(&createDefaultScheduler),
Jim Laskey13ec7022006-08-01 14:21:23 +000080 cl::desc("Instruction schedulers available:"));
81
Jim Laskey9ff542f2006-08-01 18:29:48 +000082 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000083 defaultListDAGScheduler("default", " Best scheduler for the target",
84 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000085} // namespace
86
Chris Lattner864635a2006-02-22 22:37:12 +000087namespace {
88 /// RegsForValue - This struct represents the physical registers that a
89 /// particular value is assigned and the type information about the value.
90 /// This is needed because values can be promoted into larger registers and
91 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +000092 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner864635a2006-02-22 22:37:12 +000093 /// Regs - This list hold the register (for legal and promoted values)
94 /// or register set (for expanded values) that the value should be assigned
95 /// to.
96 std::vector<unsigned> Regs;
97
98 /// RegVT - The value type of each register.
99 ///
100 MVT::ValueType RegVT;
101
102 /// ValueVT - The value type of the LLVM value, which may be promoted from
103 /// RegVT or made from merging the two expanded parts.
104 MVT::ValueType ValueVT;
105
106 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
107
108 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
109 : RegVT(regvt), ValueVT(valuevt) {
110 Regs.push_back(Reg);
111 }
112 RegsForValue(const std::vector<unsigned> &regs,
113 MVT::ValueType regvt, MVT::ValueType valuevt)
114 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
115 }
116
117 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
118 /// this value and returns the result as a ValueVT value. This uses
119 /// Chain/Flag as the input and updates them for the output Chain/Flag.
120 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000121 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000122
123 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
124 /// specified value into the registers specified by this object. This uses
125 /// Chain/Flag as the input and updates them for the output Chain/Flag.
126 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +0000127 SDOperand &Chain, SDOperand &Flag,
128 MVT::ValueType PtrVT) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000129
130 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
131 /// operand list. This adds the code marker and includes the number of
132 /// values added into it.
133 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000134 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000135 };
136}
Evan Cheng4ef10862006-01-23 07:01:07 +0000137
Chris Lattner1c08c712005-01-07 07:47:53 +0000138namespace llvm {
139 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000140 /// createDefaultScheduler - This creates an instruction scheduler appropriate
141 /// for the target.
142 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
143 SelectionDAG *DAG,
144 MachineBasicBlock *BB) {
145 TargetLowering &TLI = IS->getTargetLowering();
146
147 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
148 return createTDListDAGScheduler(IS, DAG, BB);
149 } else {
150 assert(TLI.getSchedulingPreference() ==
151 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
152 return createBURRListDAGScheduler(IS, DAG, BB);
153 }
154 }
155
156
157 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000158 /// FunctionLoweringInfo - This contains information that is global to a
159 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000160 class FunctionLoweringInfo {
161 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000162 TargetLowering &TLI;
163 Function &Fn;
164 MachineFunction &MF;
165 SSARegMap *RegMap;
166
167 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
168
169 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
170 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
171
172 /// ValueMap - Since we emit code for the function a basic block at a time,
173 /// we must remember which virtual registers hold the values for
174 /// cross-basic-block values.
175 std::map<const Value*, unsigned> ValueMap;
176
177 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
178 /// the entry block. This allows the allocas to be efficiently referenced
179 /// anywhere in the function.
180 std::map<const AllocaInst*, int> StaticAllocaMap;
181
182 unsigned MakeReg(MVT::ValueType VT) {
183 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
184 }
Chris Lattner571e4342006-10-27 21:36:01 +0000185
186 /// isExportedInst - Return true if the specified value is an instruction
187 /// exported from its block.
188 bool isExportedInst(const Value *V) {
189 return ValueMap.count(V);
190 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000191
Chris Lattner3c384492006-03-16 19:51:18 +0000192 unsigned CreateRegForValue(const Value *V);
193
Chris Lattner1c08c712005-01-07 07:47:53 +0000194 unsigned InitializeRegForValue(const Value *V) {
195 unsigned &R = ValueMap[V];
196 assert(R == 0 && "Already initialized this value register!");
197 return R = CreateRegForValue(V);
198 }
199 };
200}
201
202/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000203/// PHI nodes or outside of the basic block that defines it, or used by a
204/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000205static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
206 if (isa<PHINode>(I)) return true;
207 BasicBlock *BB = I->getParent();
208 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000209 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000210 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000211 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000212 return true;
213 return false;
214}
215
Chris Lattnerbf209482005-10-30 19:42:35 +0000216/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000217/// entry block, return true. This includes arguments used by switches, since
218/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000219static bool isOnlyUsedInEntryBlock(Argument *A) {
220 BasicBlock *Entry = A->getParent()->begin();
221 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000222 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000223 return false; // Use not in entry block.
224 return true;
225}
226
Chris Lattner1c08c712005-01-07 07:47:53 +0000227FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000228 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000229 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
230
Chris Lattnerbf209482005-10-30 19:42:35 +0000231 // Create a vreg for each argument register that is not dead and is used
232 // outside of the entry block for the function.
233 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
234 AI != E; ++AI)
235 if (!isOnlyUsedInEntryBlock(AI))
236 InitializeRegForValue(AI);
237
Chris Lattner1c08c712005-01-07 07:47:53 +0000238 // Initialize the mapping of values to registers. This is only set up for
239 // instruction values that are used outside of the block that defines
240 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000241 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000242 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
243 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000244 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000245 const Type *Ty = AI->getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +0000246 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000247 unsigned Align =
Owen Andersona69571c2006-05-03 01:29:57 +0000248 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000249 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000250
Reid Spencerb83eb642006-10-20 07:07:24 +0000251 // If the alignment of the value is smaller than the size of the
252 // value, and if the size of the value is particularly small
253 // (<= 8 bytes), round up to the size of the value for potentially
254 // better performance.
Chris Lattnera8217e32005-05-13 23:14:17 +0000255 //
256 // FIXME: This could be made better with a preferred alignment hook in
257 // TargetData. It serves primarily to 8-byte align doubles for X86.
258 if (Align < TySize && TySize <= 8) Align = TySize;
Reid Spencerb83eb642006-10-20 07:07:24 +0000259 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000260 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000261 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000262 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000263 }
264
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000265 for (; BB != EB; ++BB)
266 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000267 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
268 if (!isa<AllocaInst>(I) ||
269 !StaticAllocaMap.count(cast<AllocaInst>(I)))
270 InitializeRegForValue(I);
271
272 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
273 // also creates the initial PHI MachineInstrs, though none of the input
274 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000275 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000276 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
277 MBBMap[BB] = MBB;
278 MF.getBasicBlockList().push_back(MBB);
279
280 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
281 // appropriate.
282 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000283 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
284 if (PN->use_empty()) continue;
285
286 MVT::ValueType VT = TLI.getValueType(PN->getType());
287 unsigned NumElements;
288 if (VT != MVT::Vector)
289 NumElements = TLI.getNumElements(VT);
290 else {
291 MVT::ValueType VT1,VT2;
292 NumElements =
293 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
294 VT1, VT2);
Chris Lattnerf44fd882005-01-07 21:34:19 +0000295 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000296 unsigned PHIReg = ValueMap[PN];
297 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000298 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner8c494ab2006-10-27 23:50:33 +0000299 for (unsigned i = 0; i != NumElements; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000300 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000301 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000302 }
303}
304
Chris Lattner3c384492006-03-16 19:51:18 +0000305/// CreateRegForValue - Allocate the appropriate number of virtual registers of
306/// the correctly promoted or expanded types. Assign these registers
307/// consecutive vreg numbers and return the first assigned number.
308unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
309 MVT::ValueType VT = TLI.getValueType(V->getType());
310
311 // The number of multiples of registers that we need, to, e.g., split up
312 // a <2 x int64> -> 4 x i32 registers.
313 unsigned NumVectorRegs = 1;
314
315 // If this is a packed type, figure out what type it will decompose into
316 // and how many of the elements it will use.
317 if (VT == MVT::Vector) {
318 const PackedType *PTy = cast<PackedType>(V->getType());
319 unsigned NumElts = PTy->getNumElements();
320 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
321
322 // Divide the input until we get to a supported size. This will always
323 // end with a scalar if the target doesn't support vectors.
324 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
325 NumElts >>= 1;
326 NumVectorRegs <<= 1;
327 }
Chris Lattner6cb70042006-03-16 23:05:19 +0000328 if (NumElts == 1)
329 VT = EltTy;
330 else
331 VT = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000332 }
333
334 // The common case is that we will only create one register for this
335 // value. If we have that case, create and return the virtual register.
336 unsigned NV = TLI.getNumElements(VT);
337 if (NV == 1) {
338 // If we are promoting this value, pick the next largest supported type.
339 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
340 unsigned Reg = MakeReg(PromotedType);
341 // If this is a vector of supported or promoted types (e.g. 4 x i16),
342 // create all of the registers.
343 for (unsigned i = 1; i != NumVectorRegs; ++i)
344 MakeReg(PromotedType);
345 return Reg;
346 }
347
348 // If this value is represented with multiple target registers, make sure
349 // to create enough consecutive registers of the right (smaller) type.
350 unsigned NT = VT-1; // Find the type to use.
351 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
352 --NT;
353
354 unsigned R = MakeReg((MVT::ValueType)NT);
355 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
356 MakeReg((MVT::ValueType)NT);
357 return R;
358}
Chris Lattner1c08c712005-01-07 07:47:53 +0000359
360//===----------------------------------------------------------------------===//
361/// SelectionDAGLowering - This is the common target-independent lowering
362/// implementation that is parameterized by a TargetLowering object.
363/// Also, targets can overload any lowering method.
364///
365namespace llvm {
366class SelectionDAGLowering {
367 MachineBasicBlock *CurMBB;
368
369 std::map<const Value*, SDOperand> NodeMap;
370
Chris Lattnerd3948112005-01-17 22:19:26 +0000371 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
372 /// them up and then emit token factor nodes when possible. This allows us to
373 /// get simple disambiguation between loads without worrying about alias
374 /// analysis.
375 std::vector<SDOperand> PendingLoads;
376
Nate Begemanf15485a2006-03-27 01:32:24 +0000377 /// Case - A pair of values to record the Value for a switch case, and the
378 /// case's target basic block.
379 typedef std::pair<Constant*, MachineBasicBlock*> Case;
380 typedef std::vector<Case>::iterator CaseItr;
381 typedef std::pair<CaseItr, CaseItr> CaseRange;
382
383 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
384 /// of conditional branches.
385 struct CaseRec {
386 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
387 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
388
389 /// CaseBB - The MBB in which to emit the compare and branch
390 MachineBasicBlock *CaseBB;
391 /// LT, GE - If nonzero, we know the current case value must be less-than or
392 /// greater-than-or-equal-to these Constants.
393 Constant *LT;
394 Constant *GE;
395 /// Range - A pair of iterators representing the range of case values to be
396 /// processed at this point in the binary search tree.
397 CaseRange Range;
398 };
399
400 /// The comparison function for sorting Case values.
401 struct CaseCmp {
402 bool operator () (const Case& C1, const Case& C2) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000403 if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
404 if (I1->getType()->isUnsigned())
405 return I1->getZExtValue() <
406 cast<const ConstantInt>(C2.first)->getZExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000407
Reid Spencerb83eb642006-10-20 07:07:24 +0000408 return cast<const ConstantInt>(C1.first)->getSExtValue() <
409 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000410 }
411 };
412
Chris Lattner1c08c712005-01-07 07:47:53 +0000413public:
414 // TLI - This is information that describes the available target features we
415 // need for lowering. This indicates when operations are unavailable,
416 // implemented with a libcall, etc.
417 TargetLowering &TLI;
418 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000419 const TargetData *TD;
Chris Lattner1c08c712005-01-07 07:47:53 +0000420
Nate Begemanf15485a2006-03-27 01:32:24 +0000421 /// SwitchCases - Vector of CaseBlock structures used to communicate
422 /// SwitchInst code generation information.
423 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +0000424 SelectionDAGISel::JumpTable JT;
Nate Begemanf15485a2006-03-27 01:32:24 +0000425
Chris Lattner1c08c712005-01-07 07:47:53 +0000426 /// FuncInfo - Information about the function as a whole.
427 ///
428 FunctionLoweringInfo &FuncInfo;
429
430 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000431 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000432 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman9453eea2006-04-23 06:26:20 +0000433 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000434 }
435
Chris Lattnera651cf62005-01-17 19:43:36 +0000436 /// getRoot - Return the current virtual root of the Selection DAG.
437 ///
438 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000439 if (PendingLoads.empty())
440 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000441
Chris Lattnerd3948112005-01-17 22:19:26 +0000442 if (PendingLoads.size() == 1) {
443 SDOperand Root = PendingLoads[0];
444 DAG.setRoot(Root);
445 PendingLoads.clear();
446 return Root;
447 }
448
449 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000450 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
451 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000452 PendingLoads.clear();
453 DAG.setRoot(Root);
454 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000455 }
456
Chris Lattner571e4342006-10-27 21:36:01 +0000457 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
458
Chris Lattner1c08c712005-01-07 07:47:53 +0000459 void visit(Instruction &I) { visit(I.getOpcode(), I); }
460
461 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000462 // Note: this doesn't use InstVisitor, because it has to work with
463 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000464 switch (Opcode) {
465 default: assert(0 && "Unknown instruction type encountered!");
466 abort();
467 // Build the switch statement using the Instruction.def file.
468#define HANDLE_INST(NUM, OPCODE, CLASS) \
469 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
470#include "llvm/Instruction.def"
471 }
472 }
473
474 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
475
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000476 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000477 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000478 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000479
480 SDOperand getIntPtrConstant(uint64_t Val) {
481 return DAG.getConstant(Val, TLI.getPointerTy());
482 }
483
Chris Lattner199862b2006-03-16 19:57:50 +0000484 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000485
486 const SDOperand &setValue(const Value *V, SDOperand NewN) {
487 SDOperand &N = NodeMap[V];
488 assert(N.Val == 0 && "Already set a value for this node!");
489 return N = NewN;
490 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000491
Chris Lattner864635a2006-02-22 22:37:12 +0000492 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
493 MVT::ValueType VT,
494 bool OutReg, bool InReg,
495 std::set<unsigned> &OutputRegs,
496 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000497
Chris Lattner571e4342006-10-27 21:36:01 +0000498 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
499 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
500 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000501 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000502 void ExportFromCurrentBlock(Value *V);
503
Chris Lattner1c08c712005-01-07 07:47:53 +0000504 // Terminator instructions.
505 void visitRet(ReturnInst &I);
506 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000507 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000508 void visitUnreachable(UnreachableInst &I) { /* noop */ }
509
Nate Begemanf15485a2006-03-27 01:32:24 +0000510 // Helper for visitSwitch
511 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman37efe672006-04-22 18:53:45 +0000512 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemanf15485a2006-03-27 01:32:24 +0000513
Chris Lattner1c08c712005-01-07 07:47:53 +0000514 // These all get lowered before this pass.
Chris Lattner1c08c712005-01-07 07:47:53 +0000515 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
516 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
517
Reid Spencer1628cec2006-10-26 06:15:43 +0000518 void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
519 void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000520 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000521 void visitAdd(User &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +0000522 if (I.getType()->isFloatingPoint())
523 visitFPBinary(I, ISD::FADD, ISD::VADD);
524 else
525 visitIntBinary(I, ISD::ADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000526 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000527 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000528 void visitMul(User &I) {
529 if (I.getType()->isFloatingPoint())
530 visitFPBinary(I, ISD::FMUL, ISD::VMUL);
531 else
532 visitIntBinary(I, ISD::MUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000533 }
Reid Spencer0a783f72006-11-02 01:53:59 +0000534 void visitURem(User &I) { visitIntBinary(I, ISD::UREM, 0); }
535 void visitSRem(User &I) { visitIntBinary(I, ISD::SREM, 0); }
536 void visitFRem(User &I) { visitFPBinary (I, ISD::FREM, 0); }
Reid Spencer1628cec2006-10-26 06:15:43 +0000537 void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
538 void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
Reid Spencer0a783f72006-11-02 01:53:59 +0000539 void visitFDiv(User &I) { visitFPBinary (I, ISD::FDIV, ISD::VSDIV); }
Reid Spencer1628cec2006-10-26 06:15:43 +0000540 void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
541 void visitOr (User &I) { visitIntBinary(I, ISD::OR, ISD::VOR); }
542 void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
Nate Begemane21ea612005-11-18 07:42:56 +0000543 void visitShl(User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000544 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
545 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000546 void visitICmp(User &I);
547 void visitFCmp(User &I);
Evan Chengf6f95812006-05-23 06:40:47 +0000548 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
549 ISD::CondCode FPOpc);
550 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
551 ISD::SETOEQ); }
552 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
553 ISD::SETUNE); }
554 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
555 ISD::SETOLE); }
556 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
557 ISD::SETOGE); }
558 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
559 ISD::SETOLT); }
560 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
561 ISD::SETOGT); }
Reid Spencer3da59db2006-11-27 01:05:10 +0000562 // Visit the conversion instructions
563 void visitTrunc(User &I);
564 void visitZExt(User &I);
565 void visitSExt(User &I);
566 void visitFPTrunc(User &I);
567 void visitFPExt(User &I);
568 void visitFPToUI(User &I);
569 void visitFPToSI(User &I);
570 void visitUIToFP(User &I);
571 void visitSIToFP(User &I);
572 void visitPtrToInt(User &I);
573 void visitIntToPtr(User &I);
574 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000575
Chris Lattner2bbd8102006-03-29 00:11:43 +0000576 void visitExtractElement(User &I);
577 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000578 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000579
Chris Lattner1c08c712005-01-07 07:47:53 +0000580 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000581 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000582
583 void visitMalloc(MallocInst &I);
584 void visitFree(FreeInst &I);
585 void visitAlloca(AllocaInst &I);
586 void visitLoad(LoadInst &I);
587 void visitStore(StoreInst &I);
588 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
589 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000590 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000591 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000592 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000593
Chris Lattner1c08c712005-01-07 07:47:53 +0000594 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000595 void visitVAArg(VAArgInst &I);
596 void visitVAEnd(CallInst &I);
597 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000598 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000599
Chris Lattner7041ee32005-01-11 05:56:49 +0000600 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000601
602 void visitUserOp1(Instruction &I) {
603 assert(0 && "UserOp1 should not exist at instruction selection time!");
604 abort();
605 }
606 void visitUserOp2(Instruction &I) {
607 assert(0 && "UserOp2 should not exist at instruction selection time!");
608 abort();
609 }
610};
611} // end namespace llvm
612
Chris Lattner199862b2006-03-16 19:57:50 +0000613SDOperand SelectionDAGLowering::getValue(const Value *V) {
614 SDOperand &N = NodeMap[V];
615 if (N.Val) return N;
616
617 const Type *VTy = V->getType();
618 MVT::ValueType VT = TLI.getValueType(VTy);
619 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
620 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
621 visit(CE->getOpcode(), *CE);
622 assert(N.Val && "visit didn't populate the ValueMap!");
623 return N;
624 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
625 return N = DAG.getGlobalAddress(GV, VT);
626 } else if (isa<ConstantPointerNull>(C)) {
627 return N = DAG.getConstant(0, TLI.getPointerTy());
628 } else if (isa<UndefValue>(C)) {
Chris Lattner23d564c2006-03-19 00:20:20 +0000629 if (!isa<PackedType>(VTy))
630 return N = DAG.getNode(ISD::UNDEF, VT);
631
Chris Lattnerb2827b02006-03-19 00:52:58 +0000632 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattner23d564c2006-03-19 00:20:20 +0000633 const PackedType *PTy = cast<PackedType>(VTy);
634 unsigned NumElements = PTy->getNumElements();
635 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
636
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000637 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000638 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
639
640 // Create a VConstant node with generic Vector type.
641 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
642 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000643 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
644 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000645 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
646 return N = DAG.getConstantFP(CFP->getValue(), VT);
647 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
648 unsigned NumElements = PTy->getNumElements();
649 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000650
651 // Now that we know the number and type of the elements, push a
652 // Constant or ConstantFP node onto the ops list for each element of
653 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000654 SmallVector<SDOperand, 8> Ops;
Chris Lattner199862b2006-03-16 19:57:50 +0000655 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000656 for (unsigned i = 0; i != NumElements; ++i)
657 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000658 } else {
659 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
660 SDOperand Op;
661 if (MVT::isFloatingPoint(PVT))
662 Op = DAG.getConstantFP(0, PVT);
663 else
664 Op = DAG.getConstant(0, PVT);
665 Ops.assign(NumElements, Op);
666 }
667
Chris Lattnerb2827b02006-03-19 00:52:58 +0000668 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000669 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
670 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000671 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000672 } else {
673 // Canonicalize all constant ints to be unsigned.
Reid Spencerb83eb642006-10-20 07:07:24 +0000674 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000675 }
676 }
677
678 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
679 std::map<const AllocaInst*, int>::iterator SI =
680 FuncInfo.StaticAllocaMap.find(AI);
681 if (SI != FuncInfo.StaticAllocaMap.end())
682 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
683 }
684
685 std::map<const Value*, unsigned>::const_iterator VMI =
686 FuncInfo.ValueMap.find(V);
687 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
688
689 unsigned InReg = VMI->second;
690
691 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000692 if (VT != MVT::Vector) {
693 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000694
Chris Lattner70c2a612006-03-31 02:06:56 +0000695 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
696 if (DestVT < VT) {
697 // Source must be expanded. This input value is actually coming from the
698 // register pair VMI->second and VMI->second+1.
699 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
700 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
701 } else if (DestVT > VT) { // Promotion case
Chris Lattner199862b2006-03-16 19:57:50 +0000702 if (MVT::isFloatingPoint(VT))
703 N = DAG.getNode(ISD::FP_ROUND, VT, N);
704 else
705 N = DAG.getNode(ISD::TRUNCATE, VT, N);
706 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000707 } else {
708 // Otherwise, if this is a vector, make it available as a generic vector
709 // here.
710 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner2e2ef952006-04-05 06:54:42 +0000711 const PackedType *PTy = cast<PackedType>(VTy);
712 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000713 PTyLegalElementVT);
714
715 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000716 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000717 if (PTyElementVT == PTyLegalElementVT) {
718 // If the value types are legal, just VBUILD the CopyFromReg nodes.
719 for (unsigned i = 0; i != NE; ++i)
720 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
721 PTyElementVT));
722 } else if (PTyElementVT < PTyLegalElementVT) {
723 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
724 for (unsigned i = 0; i != NE; ++i) {
725 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
726 PTyElementVT);
727 if (MVT::isFloatingPoint(PTyElementVT))
728 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
729 else
730 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
731 Ops.push_back(Op);
732 }
733 } else {
734 // If the register was expanded, use BUILD_PAIR.
735 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
736 for (unsigned i = 0; i != NE/2; ++i) {
737 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
738 PTyElementVT);
739 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
740 PTyElementVT);
741 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
742 }
743 }
744
745 Ops.push_back(DAG.getConstant(NE, MVT::i32));
746 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000747 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000748
749 // Finally, use a VBIT_CONVERT to make this available as the appropriate
750 // vector type.
751 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
752 DAG.getConstant(PTy->getNumElements(),
753 MVT::i32),
754 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000755 }
756
757 return N;
758}
759
760
Chris Lattner1c08c712005-01-07 07:47:53 +0000761void SelectionDAGLowering::visitRet(ReturnInst &I) {
762 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000763 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000764 return;
765 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000766 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000767 NewValues.push_back(getRoot());
768 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
769 SDOperand RetOp = getValue(I.getOperand(i));
Evan Cheng8e7d0562006-05-26 23:09:09 +0000770 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begemanee625572006-01-27 21:09:22 +0000771
772 // If this is an integer return value, we need to promote it ourselves to
773 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
774 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000775 // FIXME: C calling convention requires the return type to be promoted to
776 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000777 if (MVT::isInteger(RetOp.getValueType()) &&
778 RetOp.getValueType() < MVT::i64) {
779 MVT::ValueType TmpVT;
780 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
781 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
782 else
783 TmpVT = MVT::i32;
Chris Lattner1c08c712005-01-07 07:47:53 +0000784
Evan Cheng8e7d0562006-05-26 23:09:09 +0000785 if (isSigned)
Nate Begemanee625572006-01-27 21:09:22 +0000786 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
787 else
788 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
789 }
790 NewValues.push_back(RetOp);
Evan Cheng8e7d0562006-05-26 23:09:09 +0000791 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000792 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000793 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
794 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000795}
796
Chris Lattner571e4342006-10-27 21:36:01 +0000797/// ExportFromCurrentBlock - If this condition isn't known to be exported from
798/// the current basic block, add it to ValueMap now so that we'll get a
799/// CopyTo/FromReg.
800void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
801 // No need to export constants.
802 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
803
804 // Already exported?
805 if (FuncInfo.isExportedInst(V)) return;
806
807 unsigned Reg = FuncInfo.InitializeRegForValue(V);
808 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
809}
810
Chris Lattner8c494ab2006-10-27 23:50:33 +0000811bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
812 const BasicBlock *FromBB) {
813 // The operands of the setcc have to be in this block. We don't know
814 // how to export them from some other block.
815 if (Instruction *VI = dyn_cast<Instruction>(V)) {
816 // Can export from current BB.
817 if (VI->getParent() == FromBB)
818 return true;
819
820 // Is already exported, noop.
821 return FuncInfo.isExportedInst(V);
822 }
823
824 // If this is an argument, we can export it if the BB is the entry block or
825 // if it is already exported.
826 if (isa<Argument>(V)) {
827 if (FromBB == &FromBB->getParent()->getEntryBlock())
828 return true;
829
830 // Otherwise, can only export this if it is already exported.
831 return FuncInfo.isExportedInst(V);
832 }
833
834 // Otherwise, constants can always be exported.
835 return true;
836}
837
Chris Lattner6a586c82006-10-29 21:01:20 +0000838static bool InBlock(const Value *V, const BasicBlock *BB) {
839 if (const Instruction *I = dyn_cast<Instruction>(V))
840 return I->getParent() == BB;
841 return true;
842}
843
Chris Lattner571e4342006-10-27 21:36:01 +0000844/// FindMergedConditions - If Cond is an expression like
845void SelectionDAGLowering::FindMergedConditions(Value *Cond,
846 MachineBasicBlock *TBB,
847 MachineBasicBlock *FBB,
848 MachineBasicBlock *CurBB,
849 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +0000850 // If this node is not part of the or/and tree, emit it as a branch.
851 BinaryOperator *BOp = dyn_cast<BinaryOperator>(Cond);
852
853 if (!BOp || (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +0000854 BOp->getParent() != CurBB->getBasicBlock() ||
855 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
856 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +0000857 const BasicBlock *BB = CurBB->getBasicBlock();
858
Chris Lattnerdf19f272006-10-31 22:37:42 +0000859 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Cond))
860 if ((II->getIntrinsicID() == Intrinsic::isunordered_f32 ||
861 II->getIntrinsicID() == Intrinsic::isunordered_f64) &&
862 // The operands of the setcc have to be in this block. We don't know
863 // how to export them from some other block. If this is the first
864 // block of the sequence, no exporting is needed.
865 (CurBB == CurMBB ||
866 (isExportableFromCurrentBlock(II->getOperand(1), BB) &&
867 isExportableFromCurrentBlock(II->getOperand(2), BB)))) {
868 SelectionDAGISel::CaseBlock CB(ISD::SETUO, II->getOperand(1),
869 II->getOperand(2), TBB, FBB, CurBB);
870 SwitchCases.push_back(CB);
871 return;
872 }
873
874
Chris Lattner571e4342006-10-27 21:36:01 +0000875 // If the leaf of the tree is a setcond inst, merge the condition into the
876 // caseblock.
877 if (BOp && isa<SetCondInst>(BOp) &&
878 // The operands of the setcc have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +0000879 // how to export them from some other block. If this is the first block
880 // of the sequence, no exporting is needed.
881 (CurBB == CurMBB ||
882 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
883 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Chris Lattner571e4342006-10-27 21:36:01 +0000884 ISD::CondCode SignCond, UnsCond, FPCond, Condition;
885 switch (BOp->getOpcode()) {
886 default: assert(0 && "Unknown setcc opcode!");
887 case Instruction::SetEQ:
888 SignCond = ISD::SETEQ;
889 UnsCond = ISD::SETEQ;
890 FPCond = ISD::SETOEQ;
891 break;
892 case Instruction::SetNE:
893 SignCond = ISD::SETNE;
894 UnsCond = ISD::SETNE;
895 FPCond = ISD::SETUNE;
896 break;
897 case Instruction::SetLE:
898 SignCond = ISD::SETLE;
899 UnsCond = ISD::SETULE;
900 FPCond = ISD::SETOLE;
901 break;
902 case Instruction::SetGE:
903 SignCond = ISD::SETGE;
904 UnsCond = ISD::SETUGE;
905 FPCond = ISD::SETOGE;
906 break;
907 case Instruction::SetLT:
908 SignCond = ISD::SETLT;
909 UnsCond = ISD::SETULT;
910 FPCond = ISD::SETOLT;
911 break;
912 case Instruction::SetGT:
913 SignCond = ISD::SETGT;
914 UnsCond = ISD::SETUGT;
915 FPCond = ISD::SETOGT;
916 break;
917 }
918
919 const Type *OpType = BOp->getOperand(0)->getType();
920 if (const PackedType *PTy = dyn_cast<PackedType>(OpType))
921 OpType = PTy->getElementType();
922
923 if (!FiniteOnlyFPMath() && OpType->isFloatingPoint())
924 Condition = FPCond;
925 else if (OpType->isUnsigned())
926 Condition = UnsCond;
927 else
928 Condition = SignCond;
929
930 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
931 BOp->getOperand(1), TBB, FBB, CurBB);
932 SwitchCases.push_back(CB);
933 return;
934 }
935
936 // Create a CaseBlock record representing this branch.
937 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantBool::getTrue(),
938 TBB, FBB, CurBB);
939 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +0000940 return;
941 }
942
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000943
944 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +0000945 MachineFunction::iterator BBI = CurBB;
946 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
947 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
948
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000949 if (Opc == Instruction::Or) {
950 // Codegen X | Y as:
951 // jmp_if_X TBB
952 // jmp TmpBB
953 // TmpBB:
954 // jmp_if_Y TBB
955 // jmp FBB
956 //
Chris Lattner571e4342006-10-27 21:36:01 +0000957
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000958 // Emit the LHS condition.
959 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
960
961 // Emit the RHS condition into TmpBB.
962 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
963 } else {
964 assert(Opc == Instruction::And && "Unknown merge op!");
965 // Codegen X & Y as:
966 // jmp_if_X TmpBB
967 // jmp FBB
968 // TmpBB:
969 // jmp_if_Y TBB
970 // jmp FBB
971 //
972 // This requires creation of TmpBB after CurBB.
973
974 // Emit the LHS condition.
975 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
976
977 // Emit the RHS condition into TmpBB.
978 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
979 }
Chris Lattner571e4342006-10-27 21:36:01 +0000980}
981
Chris Lattnerdf19f272006-10-31 22:37:42 +0000982/// If the set of cases should be emitted as a series of branches, return true.
983/// If we should emit this as a bunch of and/or'd together conditions, return
984/// false.
985static bool
986ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
987 if (Cases.size() != 2) return true;
988
Chris Lattner0ccb5002006-10-31 23:06:00 +0000989 // If this is two comparisons of the same values or'd or and'd together, they
990 // will get folded into a single comparison, so don't emit two blocks.
991 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
992 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
993 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
994 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
995 return false;
996 }
997
Chris Lattnerdf19f272006-10-31 22:37:42 +0000998 return true;
999}
1000
Chris Lattner1c08c712005-01-07 07:47:53 +00001001void SelectionDAGLowering::visitBr(BranchInst &I) {
1002 // Update machine-CFG edges.
1003 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001004
1005 // Figure out which block is immediately after the current one.
1006 MachineBasicBlock *NextBlock = 0;
1007 MachineFunction::iterator BBI = CurMBB;
1008 if (++BBI != CurMBB->getParent()->end())
1009 NextBlock = BBI;
1010
1011 if (I.isUnconditional()) {
1012 // If this is not a fall-through branch, emit the branch.
1013 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +00001014 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001015 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001016
Chris Lattner57ab6592006-10-24 17:57:59 +00001017 // Update machine-CFG edges.
1018 CurMBB->addSuccessor(Succ0MBB);
1019
1020 return;
1021 }
1022
1023 // If this condition is one of the special cases we handle, do special stuff
1024 // now.
1025 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001026 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001027
1028 // If this is a series of conditions that are or'd or and'd together, emit
1029 // this as a sequence of branches instead of setcc's with and/or operations.
1030 // For example, instead of something like:
1031 // cmp A, B
1032 // C = seteq
1033 // cmp D, E
1034 // F = setle
1035 // or C, F
1036 // jnz foo
1037 // Emit:
1038 // cmp A, B
1039 // je foo
1040 // cmp D, E
1041 // jle foo
1042 //
1043 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1044 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001045 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001046 BOp->getOpcode() == Instruction::Or)) {
1047 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001048 // If the compares in later blocks need to use values not currently
1049 // exported from this block, export them now. This block should always
1050 // be the first entry.
1051 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1052
Chris Lattnerdf19f272006-10-31 22:37:42 +00001053 // Allow some cases to be rejected.
1054 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001055 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1056 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1057 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1058 }
1059
1060 // Emit the branch for this block.
1061 visitSwitchCase(SwitchCases[0]);
1062 SwitchCases.erase(SwitchCases.begin());
1063 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001064 }
1065
Chris Lattner0ccb5002006-10-31 23:06:00 +00001066 // Okay, we decided not to do this, remove any inserted MBB's and clear
1067 // SwitchCases.
1068 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1069 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1070
Chris Lattnerdf19f272006-10-31 22:37:42 +00001071 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001072 }
1073 }
Chris Lattner24525952006-10-24 18:07:37 +00001074
1075 // Create a CaseBlock record representing this branch.
Chris Lattner571e4342006-10-27 21:36:01 +00001076 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
Chris Lattner24525952006-10-24 18:07:37 +00001077 Succ0MBB, Succ1MBB, CurMBB);
1078 // Use visitSwitchCase to actually insert the fast branch sequence for this
1079 // cond branch.
1080 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001081}
1082
Nate Begemanf15485a2006-03-27 01:32:24 +00001083/// visitSwitchCase - Emits the necessary code to represent a single node in
1084/// the binary search tree resulting from lowering a switch instruction.
1085void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001086 SDOperand Cond;
1087 SDOperand CondLHS = getValue(CB.CmpLHS);
1088
Chris Lattner571e4342006-10-27 21:36:01 +00001089 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1090 // handle common cases produced by branch lowering.
1091 if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner57ab6592006-10-24 17:57:59 +00001092 Cond = CondLHS;
Chris Lattner571e4342006-10-27 21:36:01 +00001093 else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
1094 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1095 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1096 } else
1097 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemanf15485a2006-03-27 01:32:24 +00001098
1099 // Set NextBlock to be the MBB immediately after the current one, if any.
1100 // This is used to avoid emitting unnecessary branches to the next block.
1101 MachineBasicBlock *NextBlock = 0;
1102 MachineFunction::iterator BBI = CurMBB;
1103 if (++BBI != CurMBB->getParent()->end())
1104 NextBlock = BBI;
1105
1106 // If the lhs block is the next block, invert the condition so that we can
1107 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001108 if (CB.TrueBB == NextBlock) {
1109 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001110 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1111 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1112 }
1113 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001114 DAG.getBasicBlock(CB.TrueBB));
1115 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001116 DAG.setRoot(BrCond);
1117 else
1118 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001119 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001120 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001121 CurMBB->addSuccessor(CB.TrueBB);
1122 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001123}
1124
Nate Begeman37efe672006-04-22 18:53:45 +00001125void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001126 // Emit the code for the jump table
1127 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001128 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1129 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1130 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1131 Table, Index));
1132 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001133}
1134
Nate Begemanf15485a2006-03-27 01:32:24 +00001135void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1136 // Figure out which block is immediately after the current one.
1137 MachineBasicBlock *NextBlock = 0;
1138 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001139
Nate Begemanf15485a2006-03-27 01:32:24 +00001140 if (++BBI != CurMBB->getParent()->end())
1141 NextBlock = BBI;
1142
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001143 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1144
Nate Begemanf15485a2006-03-27 01:32:24 +00001145 // If there is only the default destination, branch to it if it is not the
1146 // next basic block. Otherwise, just fall through.
1147 if (I.getNumOperands() == 2) {
1148 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001149
Nate Begemanf15485a2006-03-27 01:32:24 +00001150 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001151 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001152 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001153 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001154
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001155 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001156 return;
1157 }
1158
1159 // If there are any non-default case statements, create a vector of Cases
1160 // representing each one, and sort the vector so that we can efficiently
1161 // create a binary search tree from them.
1162 std::vector<Case> Cases;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001163
Nate Begemanf15485a2006-03-27 01:32:24 +00001164 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1165 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1166 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1167 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001168
Nate Begemanf15485a2006-03-27 01:32:24 +00001169 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1170
1171 // Get the Value to be switched on and default basic blocks, which will be
1172 // inserted into CaseBlock records, representing basic blocks in the binary
1173 // search tree.
1174 Value *SV = I.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001175
1176 // Get the MachineFunction which holds the current MBB. This is used during
1177 // emission of jump tables, and when inserting any additional MBBs necessary
1178 // to represent the switch.
Nate Begemanf15485a2006-03-27 01:32:24 +00001179 MachineFunction *CurMF = CurMBB->getParent();
1180 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001181
1182 // If the switch has few cases (two or less) emit a series of specific
1183 // tests.
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001184 if (Cases.size() < 3) {
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001185 // TODO: If any two of the cases has the same destination, and if one value
1186 // is the same as the other, but has one bit unset that the other has set,
1187 // use bit manipulation to do two compares at once. For example:
1188 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1189
Chris Lattnerb3543432006-10-23 18:38:22 +00001190 // Rearrange the case blocks so that the last one falls through if possible.
1191 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1192 // The last case block won't fall through into 'NextBlock' if we emit the
1193 // branches in this order. See if rearranging a case value would help.
1194 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1195 if (Cases[i].second == NextBlock) {
1196 std::swap(Cases[i], Cases.back());
1197 break;
1198 }
1199 }
1200 }
1201
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001202 // Create a CaseBlock record representing a conditional branch to
1203 // the Case's target mbb if the value being switched on SV is equal
1204 // to C.
1205 MachineBasicBlock *CurBlock = CurMBB;
1206 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1207 MachineBasicBlock *FallThrough;
1208 if (i != e-1) {
1209 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1210 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1211 } else {
1212 // If the last case doesn't match, go to the default block.
1213 FallThrough = Default;
1214 }
1215
1216 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1217 Cases[i].second, FallThrough, CurBlock);
1218
1219 // If emitting the first comparison, just call visitSwitchCase to emit the
1220 // code into the current block. Otherwise, push the CaseBlock onto the
1221 // vector to be later processed by SDISel, and insert the node's MBB
1222 // before the next MBB.
1223 if (CurBlock == CurMBB)
1224 visitSwitchCase(CB);
1225 else
1226 SwitchCases.push_back(CB);
1227
1228 CurBlock = FallThrough;
1229 }
1230 return;
1231 }
Nate Begeman37efe672006-04-22 18:53:45 +00001232
Nate Begeman17c275f2006-05-08 16:51:36 +00001233 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1234 // target supports indirect branches, then emit a jump table rather than
1235 // lowering the switch to a binary tree of conditional branches.
Evan Cheng3d4ce112006-10-30 08:00:44 +00001236 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1237 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemanf4360a42006-05-03 03:48:02 +00001238 Cases.size() > 5) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001239 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1240 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
Nate Begemanf4360a42006-05-03 03:48:02 +00001241 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1242
Nate Begeman17c275f2006-05-08 16:51:36 +00001243 if (Density >= 0.3125) {
Nate Begeman37efe672006-04-22 18:53:45 +00001244 // Create a new basic block to hold the code for loading the address
1245 // of the jump table, and jumping to it. Update successor information;
1246 // we will either branch to the default case for the switch, or the jump
1247 // table.
1248 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1249 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1250 CurMBB->addSuccessor(Default);
1251 CurMBB->addSuccessor(JumpTableBB);
1252
1253 // Subtract the lowest switch case value from the value being switched on
1254 // and conditional branch to default mbb if the result is greater than the
1255 // difference between smallest and largest cases.
1256 SDOperand SwitchOp = getValue(SV);
1257 MVT::ValueType VT = SwitchOp.getValueType();
1258 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1259 DAG.getConstant(First, VT));
1260
1261 // The SDNode we just created, which holds the value being switched on
1262 // minus the the smallest case value, needs to be copied to a virtual
1263 // register so it can be used as an index into the jump table in a
1264 // subsequent basic block. This value may be smaller or larger than the
1265 // target's pointer type, and therefore require extension or truncating.
1266 if (VT > TLI.getPointerTy())
1267 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1268 else
1269 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001270
Nate Begeman37efe672006-04-22 18:53:45 +00001271 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1272 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1273
1274 // Emit the range check for the jump table, and branch to the default
1275 // block for the switch statement if the value being switched on exceeds
1276 // the largest case in the switch.
1277 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1278 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1279 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1280 DAG.getBasicBlock(Default)));
1281
Nate Begemanf4360a42006-05-03 03:48:02 +00001282 // Build a vector of destination BBs, corresponding to each target
1283 // of the jump table. If the value of the jump table slot corresponds to
1284 // a case statement, push the case's BB onto the vector, otherwise, push
1285 // the default BB.
Nate Begeman37efe672006-04-22 18:53:45 +00001286 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemanf4360a42006-05-03 03:48:02 +00001287 uint64_t TEI = First;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001288 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Reid Spencerb83eb642006-10-20 07:07:24 +00001289 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
Nate Begemanf4360a42006-05-03 03:48:02 +00001290 DestBBs.push_back(ii->second);
Nate Begemanf4360a42006-05-03 03:48:02 +00001291 ++ii;
1292 } else {
1293 DestBBs.push_back(Default);
Nate Begemanf4360a42006-05-03 03:48:02 +00001294 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001295
Chris Lattner8c494ab2006-10-27 23:50:33 +00001296 // Update successor info. Add one edge to each unique successor.
1297 // Vector bool would be better, but vector<bool> is really slow.
1298 std::vector<unsigned char> SuccsHandled;
1299 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1300
Chris Lattnerc66764c2006-09-10 06:36:57 +00001301 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner8c494ab2006-10-27 23:50:33 +00001302 E = DestBBs.end(); I != E; ++I) {
1303 if (!SuccsHandled[(*I)->getNumber()]) {
1304 SuccsHandled[(*I)->getNumber()] = true;
1305 JumpTableBB->addSuccessor(*I);
1306 }
1307 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001308
1309 // Create a jump table index for this jump table, or return an existing
1310 // one.
Nate Begeman37efe672006-04-22 18:53:45 +00001311 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1312
1313 // Set the jump table information so that we can codegen it as a second
1314 // MachineBasicBlock
1315 JT.Reg = JumpTableReg;
1316 JT.JTI = JTI;
1317 JT.MBB = JumpTableBB;
Nate Begeman9453eea2006-04-23 06:26:20 +00001318 JT.Default = Default;
Nate Begeman37efe672006-04-22 18:53:45 +00001319 return;
1320 }
1321 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001322
1323 // Push the initial CaseRec onto the worklist
1324 std::vector<CaseRec> CaseVec;
1325 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1326
1327 while (!CaseVec.empty()) {
1328 // Grab a record representing a case range to process off the worklist
1329 CaseRec CR = CaseVec.back();
1330 CaseVec.pop_back();
1331
1332 // Size is the number of Cases represented by this range. If Size is 1,
1333 // then we are processing a leaf of the binary search tree. Otherwise,
1334 // we need to pick a pivot, and push left and right ranges onto the
1335 // worklist.
1336 unsigned Size = CR.Range.second - CR.Range.first;
1337
1338 if (Size == 1) {
1339 // Create a CaseBlock record representing a conditional branch to
1340 // the Case's target mbb if the value being switched on SV is equal
1341 // to C. Otherwise, branch to default.
1342 Constant *C = CR.Range.first->first;
1343 MachineBasicBlock *Target = CR.Range.first->second;
1344 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1345 CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001346
Nate Begemanf15485a2006-03-27 01:32:24 +00001347 // If the MBB representing the leaf node is the current MBB, then just
1348 // call visitSwitchCase to emit the code into the current block.
1349 // Otherwise, push the CaseBlock onto the vector to be later processed
1350 // by SDISel, and insert the node's MBB before the next MBB.
1351 if (CR.CaseBB == CurMBB)
1352 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001353 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001354 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001355 } else {
1356 // split case range at pivot
1357 CaseItr Pivot = CR.Range.first + (Size / 2);
1358 CaseRange LHSR(CR.Range.first, Pivot);
1359 CaseRange RHSR(Pivot, CR.Range.second);
1360 Constant *C = Pivot->first;
Chris Lattner57ab6592006-10-24 17:57:59 +00001361 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001362
Nate Begemanf15485a2006-03-27 01:32:24 +00001363 // We know that we branch to the LHS if the Value being switched on is
1364 // less than the Pivot value, C. We use this to optimize our binary
1365 // tree a bit, by recognizing that if SV is greater than or equal to the
1366 // LHS's Case Value, and that Case Value is exactly one less than the
1367 // Pivot's Value, then we can branch directly to the LHS's Target,
1368 // rather than creating a leaf node for it.
1369 if ((LHSR.second - LHSR.first) == 1 &&
1370 LHSR.first->first == CR.GE &&
Reid Spencerb83eb642006-10-20 07:07:24 +00001371 cast<ConstantIntegral>(C)->getZExtValue() ==
1372 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001373 TrueBB = LHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001374 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001375 TrueBB = new MachineBasicBlock(LLVMBB);
1376 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1377 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001378 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001379
Nate Begemanf15485a2006-03-27 01:32:24 +00001380 // Similar to the optimization above, if the Value being switched on is
1381 // known to be less than the Constant CR.LT, and the current Case Value
1382 // is CR.LT - 1, then we can branch directly to the target block for
1383 // the current Case Value, rather than emitting a RHS leaf node for it.
1384 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Reid Spencerb83eb642006-10-20 07:07:24 +00001385 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1386 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001387 FalseBB = RHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001388 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001389 FalseBB = new MachineBasicBlock(LLVMBB);
1390 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1391 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001392 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001393
Nate Begemanf15485a2006-03-27 01:32:24 +00001394 // Create a CaseBlock record representing a conditional branch to
1395 // the LHS node if the value being switched on SV is less than C.
1396 // Otherwise, branch to LHS.
1397 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
Chris Lattner57ab6592006-10-24 17:57:59 +00001398 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001399
Nate Begemanf15485a2006-03-27 01:32:24 +00001400 if (CR.CaseBB == CurMBB)
1401 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001402 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001403 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001404 }
1405 }
1406}
1407
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001408void SelectionDAGLowering::visitSub(User &I) {
1409 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +00001410 if (I.getType()->isFloatingPoint()) {
1411 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1412 if (CFP->isExactlyValue(-0.0)) {
1413 SDOperand Op2 = getValue(I.getOperand(1));
1414 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1415 return;
1416 }
Reid Spencer1628cec2006-10-26 06:15:43 +00001417 visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1418 } else
1419 visitIntBinary(I, ISD::SUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001420}
1421
Reid Spencer1628cec2006-10-26 06:15:43 +00001422void
1423SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001424 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001425 SDOperand Op1 = getValue(I.getOperand(0));
1426 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +00001427
Reid Spencer1628cec2006-10-26 06:15:43 +00001428 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001429 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1430 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1431 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Reid Spencer1628cec2006-10-26 06:15:43 +00001432 } else {
1433 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1434 }
1435}
1436
1437void
1438SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1439 const Type *Ty = I.getType();
1440 SDOperand Op1 = getValue(I.getOperand(0));
1441 SDOperand Op2 = getValue(I.getOperand(1));
1442
1443 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1444 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1445 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1446 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1447 } else {
1448 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001449 }
Nate Begemane21ea612005-11-18 07:42:56 +00001450}
Chris Lattner2c49f272005-01-19 22:31:21 +00001451
Nate Begemane21ea612005-11-18 07:42:56 +00001452void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1453 SDOperand Op1 = getValue(I.getOperand(0));
1454 SDOperand Op2 = getValue(I.getOperand(1));
1455
1456 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1457
Chris Lattner1c08c712005-01-07 07:47:53 +00001458 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1459}
1460
Reid Spencer45fb3f32006-11-20 01:22:35 +00001461void SelectionDAGLowering::visitICmp(User &I) {
1462 ICmpInst *IC = cast<ICmpInst>(&I);
1463 SDOperand Op1 = getValue(IC->getOperand(0));
1464 SDOperand Op2 = getValue(IC->getOperand(1));
1465 ISD::CondCode Opcode;
1466 switch (IC->getPredicate()) {
1467 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1468 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1469 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1470 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1471 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1472 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1473 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1474 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1475 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1476 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1477 default:
1478 assert(!"Invalid ICmp predicate value");
1479 Opcode = ISD::SETEQ;
1480 break;
1481 }
1482 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1483}
1484
1485void SelectionDAGLowering::visitFCmp(User &I) {
1486 FCmpInst *FC = cast<FCmpInst>(&I);
1487 SDOperand Op1 = getValue(FC->getOperand(0));
1488 SDOperand Op2 = getValue(FC->getOperand(1));
1489 ISD::CondCode Opcode;
1490 switch (FC->getPredicate()) {
1491 case FCmpInst::FCMP_FALSE : Opcode = ISD::SETFALSE;
1492 case FCmpInst::FCMP_OEQ : Opcode = ISD::SETOEQ;
1493 case FCmpInst::FCMP_OGT : Opcode = ISD::SETOGT;
1494 case FCmpInst::FCMP_OGE : Opcode = ISD::SETOGE;
1495 case FCmpInst::FCMP_OLT : Opcode = ISD::SETOLT;
1496 case FCmpInst::FCMP_OLE : Opcode = ISD::SETOLE;
1497 case FCmpInst::FCMP_ONE : Opcode = ISD::SETONE;
1498 case FCmpInst::FCMP_ORD : Opcode = ISD::SETO;
1499 case FCmpInst::FCMP_UNO : Opcode = ISD::SETUO;
1500 case FCmpInst::FCMP_UEQ : Opcode = ISD::SETUEQ;
1501 case FCmpInst::FCMP_UGT : Opcode = ISD::SETUGT;
1502 case FCmpInst::FCMP_UGE : Opcode = ISD::SETUGE;
1503 case FCmpInst::FCMP_ULT : Opcode = ISD::SETULT;
1504 case FCmpInst::FCMP_ULE : Opcode = ISD::SETULE;
1505 case FCmpInst::FCMP_UNE : Opcode = ISD::SETUNE;
1506 case FCmpInst::FCMP_TRUE : Opcode = ISD::SETTRUE;
1507 default:
1508 assert(!"Invalid FCmp predicate value");
1509 Opcode = ISD::SETFALSE;
1510 break;
1511 }
1512 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1513}
1514
Chris Lattner1c08c712005-01-07 07:47:53 +00001515void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
Evan Chengf6f95812006-05-23 06:40:47 +00001516 ISD::CondCode UnsignedOpcode,
1517 ISD::CondCode FPOpcode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001518 SDOperand Op1 = getValue(I.getOperand(0));
1519 SDOperand Op2 = getValue(I.getOperand(1));
1520 ISD::CondCode Opcode = SignedOpcode;
Evan Cheng80235d52006-05-23 18:18:46 +00001521 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
Evan Chengf6f95812006-05-23 06:40:47 +00001522 Opcode = FPOpcode;
1523 else if (I.getOperand(0)->getType()->isUnsigned())
Chris Lattner1c08c712005-01-07 07:47:53 +00001524 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +00001525 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +00001526}
1527
1528void SelectionDAGLowering::visitSelect(User &I) {
1529 SDOperand Cond = getValue(I.getOperand(0));
1530 SDOperand TrueVal = getValue(I.getOperand(1));
1531 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattnerb22e35a2006-04-08 22:22:57 +00001532 if (!isa<PackedType>(I.getType())) {
1533 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1534 TrueVal, FalseVal));
1535 } else {
1536 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1537 *(TrueVal.Val->op_end()-2),
1538 *(TrueVal.Val->op_end()-1)));
1539 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001540}
1541
Reid Spencer3da59db2006-11-27 01:05:10 +00001542
1543void SelectionDAGLowering::visitTrunc(User &I) {
1544 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1545 SDOperand N = getValue(I.getOperand(0));
1546 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1547 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1548}
1549
1550void SelectionDAGLowering::visitZExt(User &I) {
1551 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1552 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1553 SDOperand N = getValue(I.getOperand(0));
1554 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1555 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1556}
1557
1558void SelectionDAGLowering::visitSExt(User &I) {
1559 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1560 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1561 SDOperand N = getValue(I.getOperand(0));
1562 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1563 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1564}
1565
1566void SelectionDAGLowering::visitFPTrunc(User &I) {
1567 // FPTrunc is never a no-op cast, no need to check
1568 SDOperand N = getValue(I.getOperand(0));
1569 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1570 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1571}
1572
1573void SelectionDAGLowering::visitFPExt(User &I){
1574 // FPTrunc is never a no-op cast, no need to check
1575 SDOperand N = getValue(I.getOperand(0));
1576 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1577 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1578}
1579
1580void SelectionDAGLowering::visitFPToUI(User &I) {
1581 // FPToUI is never a no-op cast, no need to check
1582 SDOperand N = getValue(I.getOperand(0));
1583 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1584 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1585}
1586
1587void SelectionDAGLowering::visitFPToSI(User &I) {
1588 // FPToSI is never a no-op cast, no need to check
1589 SDOperand N = getValue(I.getOperand(0));
1590 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1591 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1592}
1593
1594void SelectionDAGLowering::visitUIToFP(User &I) {
1595 // UIToFP is never a no-op cast, no need to check
1596 SDOperand N = getValue(I.getOperand(0));
1597 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1598 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1599}
1600
1601void SelectionDAGLowering::visitSIToFP(User &I){
1602 // UIToFP is never a no-op cast, no need to check
1603 SDOperand N = getValue(I.getOperand(0));
1604 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1605 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1606}
1607
1608void SelectionDAGLowering::visitPtrToInt(User &I) {
1609 // What to do depends on the size of the integer and the size of the pointer.
1610 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00001611 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00001612 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001613 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001614 SDOperand Result;
1615 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1616 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1617 else
1618 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1619 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1620 setValue(&I, Result);
1621}
Chris Lattner1c08c712005-01-07 07:47:53 +00001622
Reid Spencer3da59db2006-11-27 01:05:10 +00001623void SelectionDAGLowering::visitIntToPtr(User &I) {
1624 // What to do depends on the size of the integer and the size of the pointer.
1625 // We can either truncate, zero extend, or no-op, accordingly.
1626 SDOperand N = getValue(I.getOperand(0));
1627 MVT::ValueType SrcVT = N.getValueType();
1628 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1629 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1630 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1631 else
1632 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1633 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1634}
1635
1636void SelectionDAGLowering::visitBitCast(User &I) {
1637 SDOperand N = getValue(I.getOperand(0));
1638 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00001639 if (DestVT == MVT::Vector) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001640 // This is a cast to a vector from something else.
1641 // Get information about the output vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001642 const PackedType *DestTy = cast<PackedType>(I.getType());
1643 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1644 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1645 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1646 DAG.getValueType(EltVT)));
Reid Spencer3da59db2006-11-27 01:05:10 +00001647 return;
1648 }
1649 MVT::ValueType SrcVT = N.getValueType();
1650 if (SrcVT == MVT::Vector) {
1651 // This is a cast from a vctor to something else.
1652 // Get information about the input vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001653 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer3da59db2006-11-27 01:05:10 +00001654 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00001655 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001656
1657 // BitCast assures us that source and destination are the same size so this
1658 // is either a BIT_CONVERT or a no-op.
1659 if (DestVT != N.getValueType())
1660 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1661 else
1662 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00001663}
1664
Chris Lattner2bbd8102006-03-29 00:11:43 +00001665void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001666 SDOperand InVec = getValue(I.getOperand(0));
1667 SDOperand InVal = getValue(I.getOperand(1));
1668 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1669 getValue(I.getOperand(2)));
1670
Chris Lattner2332b9f2006-03-19 01:17:20 +00001671 SDOperand Num = *(InVec.Val->op_end()-2);
1672 SDOperand Typ = *(InVec.Val->op_end()-1);
1673 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1674 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00001675}
1676
Chris Lattner2bbd8102006-03-29 00:11:43 +00001677void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00001678 SDOperand InVec = getValue(I.getOperand(0));
1679 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1680 getValue(I.getOperand(1)));
1681 SDOperand Typ = *(InVec.Val->op_end()-1);
1682 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1683 TLI.getValueType(I.getType()), InVec, InIdx));
1684}
Chris Lattnerc7029802006-03-18 01:44:44 +00001685
Chris Lattner3e104b12006-04-08 04:15:24 +00001686void SelectionDAGLowering::visitShuffleVector(User &I) {
1687 SDOperand V1 = getValue(I.getOperand(0));
1688 SDOperand V2 = getValue(I.getOperand(1));
1689 SDOperand Mask = getValue(I.getOperand(2));
1690
1691 SDOperand Num = *(V1.Val->op_end()-2);
1692 SDOperand Typ = *(V2.Val->op_end()-1);
1693 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1694 V1, V2, Mask, Num, Typ));
1695}
1696
1697
Chris Lattner1c08c712005-01-07 07:47:53 +00001698void SelectionDAGLowering::visitGetElementPtr(User &I) {
1699 SDOperand N = getValue(I.getOperand(0));
1700 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001701
1702 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1703 OI != E; ++OI) {
1704 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001705 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001706 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00001707 if (Field) {
1708 // N = N + Offset
Owen Andersona69571c2006-05-03 01:29:57 +00001709 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner1c08c712005-01-07 07:47:53 +00001710 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001711 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00001712 }
1713 Ty = StTy->getElementType(Field);
1714 } else {
1715 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00001716
Chris Lattner7c0104b2005-11-09 04:45:33 +00001717 // If this is a constant subscript, handle it quickly.
1718 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001719 if (CI->getZExtValue() == 0) continue;
Chris Lattner7c0104b2005-11-09 04:45:33 +00001720 uint64_t Offs;
Reid Spencerb83eb642006-10-20 07:07:24 +00001721 if (CI->getType()->isSigned())
1722 Offs = (int64_t)
1723 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001724 else
Reid Spencerb83eb642006-10-20 07:07:24 +00001725 Offs =
1726 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001727 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1728 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00001729 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00001730
1731 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00001732 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001733 SDOperand IdxN = getValue(Idx);
1734
1735 // If the index is smaller or larger than intptr_t, truncate or extend
1736 // it.
1737 if (IdxN.getValueType() < N.getValueType()) {
1738 if (Idx->getType()->isSigned())
1739 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1740 else
1741 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1742 } else if (IdxN.getValueType() > N.getValueType())
1743 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1744
1745 // If this is a multiply by a power of two, turn it into a shl
1746 // immediately. This is a very common case.
1747 if (isPowerOf2_64(ElementSize)) {
1748 unsigned Amt = Log2_64(ElementSize);
1749 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00001750 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00001751 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1752 continue;
1753 }
1754
1755 SDOperand Scale = getIntPtrConstant(ElementSize);
1756 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1757 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00001758 }
1759 }
1760 setValue(&I, N);
1761}
1762
1763void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1764 // If this is a fixed sized alloca in the entry block of the function,
1765 // allocate it statically on the stack.
1766 if (FuncInfo.StaticAllocaMap.count(&I))
1767 return; // getValue will auto-populate this.
1768
1769 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00001770 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1771 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +00001772 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00001773
1774 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00001775 MVT::ValueType IntPtr = TLI.getPointerTy();
1776 if (IntPtr < AllocSize.getValueType())
1777 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1778 else if (IntPtr > AllocSize.getValueType())
1779 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00001780
Chris Lattner68cd65e2005-01-22 23:04:37 +00001781 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00001782 getIntPtrConstant(TySize));
1783
1784 // Handle alignment. If the requested alignment is less than or equal to the
1785 // stack alignment, ignore it and round the size of the allocation up to the
1786 // stack alignment size. If the size is greater than the stack alignment, we
1787 // note this in the DYNAMIC_STACKALLOC node.
1788 unsigned StackAlign =
1789 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1790 if (Align <= StackAlign) {
1791 Align = 0;
1792 // Add SA-1 to the size.
1793 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1794 getIntPtrConstant(StackAlign-1));
1795 // Mask out the low bits for alignment purposes.
1796 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1797 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1798 }
1799
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001800 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001801 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1802 MVT::Other);
1803 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner1c08c712005-01-07 07:47:53 +00001804 DAG.setRoot(setValue(&I, DSA).getValue(1));
1805
1806 // Inform the Frame Information that we have just allocated a variable-sized
1807 // object.
1808 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1809}
1810
Chris Lattner1c08c712005-01-07 07:47:53 +00001811void SelectionDAGLowering::visitLoad(LoadInst &I) {
1812 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00001813
Chris Lattnerd3948112005-01-17 22:19:26 +00001814 SDOperand Root;
1815 if (I.isVolatile())
1816 Root = getRoot();
1817 else {
1818 // Do not serialize non-volatile loads against each other.
1819 Root = DAG.getRoot();
1820 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001821
Evan Cheng466685d2006-10-09 20:57:25 +00001822 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001823 Root, I.isVolatile()));
1824}
1825
1826SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00001827 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001828 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001829 SDOperand L;
Nate Begeman8cfa57b2005-12-06 06:18:55 +00001830 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00001831 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00001832 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1833 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001834 } else {
Evan Cheng466685d2006-10-09 20:57:25 +00001835 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001836 }
Chris Lattnerd3948112005-01-17 22:19:26 +00001837
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001838 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00001839 DAG.setRoot(L.getValue(1));
1840 else
1841 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001842
1843 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00001844}
1845
1846
1847void SelectionDAGLowering::visitStore(StoreInst &I) {
1848 Value *SrcV = I.getOperand(0);
1849 SDOperand Src = getValue(SrcV);
1850 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng8b2794a2006-10-13 21:14:26 +00001851 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1852 I.isVolatile()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001853}
1854
Chris Lattner0eade312006-03-24 02:22:33 +00001855/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1856/// access memory and has no other side effects at all.
1857static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1858#define GET_NO_MEMORY_INTRINSICS
1859#include "llvm/Intrinsics.gen"
1860#undef GET_NO_MEMORY_INTRINSICS
1861 return false;
1862}
1863
Chris Lattnere58a7802006-04-02 03:41:14 +00001864// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1865// have any side-effects or if it only reads memory.
1866static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1867#define GET_SIDE_EFFECT_INFO
1868#include "llvm/Intrinsics.gen"
1869#undef GET_SIDE_EFFECT_INFO
1870 return false;
1871}
1872
Chris Lattner0eade312006-03-24 02:22:33 +00001873/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1874/// node.
1875void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1876 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00001877 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00001878 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00001879
1880 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001881 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00001882 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1883 if (OnlyLoad) {
1884 // We don't need to serialize loads against other loads.
1885 Ops.push_back(DAG.getRoot());
1886 } else {
1887 Ops.push_back(getRoot());
1888 }
1889 }
Chris Lattner0eade312006-03-24 02:22:33 +00001890
1891 // Add the intrinsic ID as an integer operand.
1892 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1893
1894 // Add all operands of the call to the operand list.
1895 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1896 SDOperand Op = getValue(I.getOperand(i));
1897
1898 // If this is a vector type, force it to the right packed type.
1899 if (Op.getValueType() == MVT::Vector) {
1900 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1901 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1902
1903 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1904 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1905 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1906 }
1907
1908 assert(TLI.isTypeLegal(Op.getValueType()) &&
1909 "Intrinsic uses a non-legal type?");
1910 Ops.push_back(Op);
1911 }
1912
1913 std::vector<MVT::ValueType> VTs;
1914 if (I.getType() != Type::VoidTy) {
1915 MVT::ValueType VT = TLI.getValueType(I.getType());
1916 if (VT == MVT::Vector) {
1917 const PackedType *DestTy = cast<PackedType>(I.getType());
1918 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1919
1920 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1921 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1922 }
1923
1924 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1925 VTs.push_back(VT);
1926 }
1927 if (HasChain)
1928 VTs.push_back(MVT::Other);
1929
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001930 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1931
Chris Lattner0eade312006-03-24 02:22:33 +00001932 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00001933 SDOperand Result;
1934 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001935 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1936 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001937 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001938 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1939 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001940 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001941 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1942 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001943
Chris Lattnere58a7802006-04-02 03:41:14 +00001944 if (HasChain) {
1945 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1946 if (OnlyLoad)
1947 PendingLoads.push_back(Chain);
1948 else
1949 DAG.setRoot(Chain);
1950 }
Chris Lattner0eade312006-03-24 02:22:33 +00001951 if (I.getType() != Type::VoidTy) {
1952 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1953 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1954 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1955 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1956 DAG.getValueType(EVT));
1957 }
1958 setValue(&I, Result);
1959 }
1960}
1961
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001962/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1963/// we want to emit this as a call to a named external function, return the name
1964/// otherwise lower it and return null.
1965const char *
1966SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1967 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00001968 default:
1969 // By default, turn this into a target intrinsic node.
1970 visitTargetIntrinsic(I, Intrinsic);
1971 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001972 case Intrinsic::vastart: visitVAStart(I); return 0;
1973 case Intrinsic::vaend: visitVAEnd(I); return 0;
1974 case Intrinsic::vacopy: visitVACopy(I); return 0;
1975 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1976 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1977 case Intrinsic::setjmp:
1978 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1979 break;
1980 case Intrinsic::longjmp:
1981 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1982 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00001983 case Intrinsic::memcpy_i32:
1984 case Intrinsic::memcpy_i64:
1985 visitMemIntrinsic(I, ISD::MEMCPY);
1986 return 0;
1987 case Intrinsic::memset_i32:
1988 case Intrinsic::memset_i64:
1989 visitMemIntrinsic(I, ISD::MEMSET);
1990 return 0;
1991 case Intrinsic::memmove_i32:
1992 case Intrinsic::memmove_i64:
1993 visitMemIntrinsic(I, ISD::MEMMOVE);
1994 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001995
Chris Lattner86cb6432005-12-13 17:40:33 +00001996 case Intrinsic::dbg_stoppoint: {
Jim Laskeyce72b172006-02-11 01:01:30 +00001997 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001998 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001999 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002000 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002001
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002002 Ops[0] = getRoot();
2003 Ops[1] = getValue(SPI.getLineValue());
2004 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002005
Jim Laskey43970fe2006-03-23 18:06:46 +00002006 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002007 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002008 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2009
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002010 Ops[3] = DAG.getString(CompileUnit->getFileName());
2011 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002012
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002013 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002014 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002015
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002016 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002017 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002018 case Intrinsic::dbg_region_start: {
2019 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2020 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00002021 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00002022 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002023 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
2024 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002025 }
2026
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002027 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002028 }
2029 case Intrinsic::dbg_region_end: {
2030 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2031 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00002032 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00002033 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002034 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
2035 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002036 }
2037
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002038 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002039 }
2040 case Intrinsic::dbg_func_start: {
2041 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2042 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00002043 if (DebugInfo && FSI.getSubprogram() &&
2044 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00002045 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002046 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
2047 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002048 }
2049
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002050 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002051 }
2052 case Intrinsic::dbg_declare: {
2053 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
2054 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeybf7637d2006-03-28 13:45:20 +00002055 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00002056 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002057 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey43970fe2006-03-23 18:06:46 +00002058 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00002059 }
2060
2061 return 0;
2062 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002063
Reid Spencer0b118202006-01-16 21:12:35 +00002064 case Intrinsic::isunordered_f32:
2065 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002066 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
2067 getValue(I.getOperand(2)), ISD::SETUO));
2068 return 0;
2069
Reid Spencer0b118202006-01-16 21:12:35 +00002070 case Intrinsic::sqrt_f32:
2071 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002072 setValue(&I, DAG.getNode(ISD::FSQRT,
2073 getValue(I.getOperand(1)).getValueType(),
2074 getValue(I.getOperand(1))));
2075 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00002076 case Intrinsic::powi_f32:
2077 case Intrinsic::powi_f64:
2078 setValue(&I, DAG.getNode(ISD::FPOWI,
2079 getValue(I.getOperand(1)).getValueType(),
2080 getValue(I.getOperand(1)),
2081 getValue(I.getOperand(2))));
2082 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002083 case Intrinsic::pcmarker: {
2084 SDOperand Tmp = getValue(I.getOperand(1));
2085 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2086 return 0;
2087 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002088 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002089 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002090 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2091 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2092 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002093 setValue(&I, Tmp);
2094 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00002095 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002096 }
Nate Begemand88fc032006-01-14 03:14:10 +00002097 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00002098 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00002099 case Intrinsic::bswap_i64:
2100 setValue(&I, DAG.getNode(ISD::BSWAP,
2101 getValue(I.getOperand(1)).getValueType(),
2102 getValue(I.getOperand(1))));
2103 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002104 case Intrinsic::cttz_i8:
2105 case Intrinsic::cttz_i16:
2106 case Intrinsic::cttz_i32:
2107 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002108 setValue(&I, DAG.getNode(ISD::CTTZ,
2109 getValue(I.getOperand(1)).getValueType(),
2110 getValue(I.getOperand(1))));
2111 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002112 case Intrinsic::ctlz_i8:
2113 case Intrinsic::ctlz_i16:
2114 case Intrinsic::ctlz_i32:
2115 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002116 setValue(&I, DAG.getNode(ISD::CTLZ,
2117 getValue(I.getOperand(1)).getValueType(),
2118 getValue(I.getOperand(1))));
2119 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002120 case Intrinsic::ctpop_i8:
2121 case Intrinsic::ctpop_i16:
2122 case Intrinsic::ctpop_i32:
2123 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002124 setValue(&I, DAG.getNode(ISD::CTPOP,
2125 getValue(I.getOperand(1)).getValueType(),
2126 getValue(I.getOperand(1))));
2127 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00002128 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002129 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002130 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2131 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002132 setValue(&I, Tmp);
2133 DAG.setRoot(Tmp.getValue(1));
2134 return 0;
2135 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002136 case Intrinsic::stackrestore: {
2137 SDOperand Tmp = getValue(I.getOperand(1));
2138 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002139 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002140 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002141 case Intrinsic::prefetch:
2142 // FIXME: Currently discarding prefetches.
2143 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002144 }
2145}
2146
2147
Chris Lattner1c08c712005-01-07 07:47:53 +00002148void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002149 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002150 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002151 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002152 if (unsigned IID = F->getIntrinsicID()) {
2153 RenameFn = visitIntrinsicCall(I, IID);
2154 if (!RenameFn)
2155 return;
2156 } else { // Not an LLVM intrinsic.
2157 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002158 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2159 if (I.getNumOperands() == 3 && // Basic sanity checks.
2160 I.getOperand(1)->getType()->isFloatingPoint() &&
2161 I.getType() == I.getOperand(1)->getType() &&
2162 I.getType() == I.getOperand(2)->getType()) {
2163 SDOperand LHS = getValue(I.getOperand(1));
2164 SDOperand RHS = getValue(I.getOperand(2));
2165 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2166 LHS, RHS));
2167 return;
2168 }
2169 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002170 if (I.getNumOperands() == 2 && // Basic sanity checks.
2171 I.getOperand(1)->getType()->isFloatingPoint() &&
2172 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002173 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002174 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2175 return;
2176 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002177 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002178 if (I.getNumOperands() == 2 && // Basic sanity checks.
2179 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002180 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002181 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002182 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2183 return;
2184 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002185 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002186 if (I.getNumOperands() == 2 && // Basic sanity checks.
2187 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002188 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002189 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002190 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2191 return;
2192 }
2193 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00002194 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002195 } else if (isa<InlineAsm>(I.getOperand(0))) {
2196 visitInlineAsm(I);
2197 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002198 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002199
Chris Lattner64e14b12005-01-08 22:48:57 +00002200 SDOperand Callee;
2201 if (!RenameFn)
2202 Callee = getValue(I.getOperand(0));
2203 else
2204 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00002205 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002206 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00002207 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2208 Value *Arg = I.getOperand(i);
2209 SDOperand ArgNode = getValue(Arg);
2210 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
2211 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002212
Nate Begeman8e21e712005-03-26 01:29:23 +00002213 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2214 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00002215
Chris Lattnercf5734d2005-01-08 19:26:18 +00002216 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00002217 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00002218 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00002219 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00002220 setValue(&I, Result.first);
2221 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002222}
2223
Chris Lattner864635a2006-02-22 22:37:12 +00002224SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002225 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002226 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2227 Chain = Val.getValue(1);
2228 Flag = Val.getValue(2);
2229
2230 // If the result was expanded, copy from the top part.
2231 if (Regs.size() > 1) {
2232 assert(Regs.size() == 2 &&
2233 "Cannot expand to more than 2 elts yet!");
2234 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002235 Chain = Hi.getValue(1);
2236 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002237 if (DAG.getTargetLoweringInfo().isLittleEndian())
2238 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2239 else
2240 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002241 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002242
Chris Lattnercf752aa2006-06-08 18:22:48 +00002243 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002244 // appropriate type.
2245 if (RegVT == ValueVT)
2246 return Val;
2247
Chris Lattnercf752aa2006-06-08 18:22:48 +00002248 if (MVT::isInteger(RegVT)) {
2249 if (ValueVT < RegVT)
2250 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2251 else
2252 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2253 } else {
Chris Lattner864635a2006-02-22 22:37:12 +00002254 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002255 }
Chris Lattner864635a2006-02-22 22:37:12 +00002256}
2257
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002258/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2259/// specified value into the registers specified by this object. This uses
2260/// Chain/Flag as the input and updates them for the output Chain/Flag.
2261void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002262 SDOperand &Chain, SDOperand &Flag,
2263 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002264 if (Regs.size() == 1) {
2265 // If there is a single register and the types differ, this must be
2266 // a promotion.
2267 if (RegVT != ValueVT) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002268 if (MVT::isInteger(RegVT)) {
2269 if (RegVT < ValueVT)
2270 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2271 else
2272 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2273 } else
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002274 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2275 }
2276 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2277 Flag = Chain.getValue(1);
2278 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002279 std::vector<unsigned> R(Regs);
2280 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2281 std::reverse(R.begin(), R.end());
2282
2283 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002284 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002285 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002286 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002287 Flag = Chain.getValue(1);
2288 }
2289 }
2290}
Chris Lattner864635a2006-02-22 22:37:12 +00002291
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002292/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2293/// operand list. This adds the code marker and includes the number of
2294/// values added into it.
2295void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002296 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002297 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2298 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2299 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2300}
Chris Lattner864635a2006-02-22 22:37:12 +00002301
2302/// isAllocatableRegister - If the specified register is safe to allocate,
2303/// i.e. it isn't a stack pointer or some other special register, return the
2304/// register class for the register. Otherwise, return null.
2305static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002306isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2307 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002308 MVT::ValueType FoundVT = MVT::Other;
2309 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002310 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2311 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002312 MVT::ValueType ThisVT = MVT::Other;
2313
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002314 const TargetRegisterClass *RC = *RCI;
2315 // If none of the the value types for this register class are valid, we
2316 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002317 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2318 I != E; ++I) {
2319 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002320 // If we have already found this register in a different register class,
2321 // choose the one with the largest VT specified. For example, on
2322 // PowerPC, we favor f64 register classes over f32.
2323 if (FoundVT == MVT::Other ||
2324 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2325 ThisVT = *I;
2326 break;
2327 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002328 }
2329 }
2330
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002331 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002332
Chris Lattner864635a2006-02-22 22:37:12 +00002333 // NOTE: This isn't ideal. In particular, this might allocate the
2334 // frame pointer in functions that need it (due to them not being taken
2335 // out of allocation, because a variable sized allocation hasn't been seen
2336 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002337 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2338 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002339 if (*I == Reg) {
2340 // We found a matching register class. Keep looking at others in case
2341 // we find one with larger registers that this physreg is also in.
2342 FoundRC = RC;
2343 FoundVT = ThisVT;
2344 break;
2345 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002346 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002347 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00002348}
2349
2350RegsForValue SelectionDAGLowering::
2351GetRegistersForValue(const std::string &ConstrCode,
2352 MVT::ValueType VT, bool isOutReg, bool isInReg,
2353 std::set<unsigned> &OutputRegs,
2354 std::set<unsigned> &InputRegs) {
2355 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2356 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2357 std::vector<unsigned> Regs;
2358
2359 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2360 MVT::ValueType RegVT;
2361 MVT::ValueType ValueVT = VT;
2362
Chris Lattner2a821602006-11-02 01:41:49 +00002363 // If this is a constraint for a specific physical register, like {r17},
2364 // assign it now.
Chris Lattner864635a2006-02-22 22:37:12 +00002365 if (PhysReg.first) {
2366 if (VT == MVT::Other)
2367 ValueVT = *PhysReg.second->vt_begin();
Chris Lattnercf752aa2006-06-08 18:22:48 +00002368
2369 // Get the actual register value type. This is important, because the user
2370 // may have asked for (e.g.) the AX register in i32 type. We need to
2371 // remember that AX is actually i16 to get the right extension.
2372 RegVT = *PhysReg.second->vt_begin();
Chris Lattner864635a2006-02-22 22:37:12 +00002373
2374 // This is a explicit reference to a physical register.
2375 Regs.push_back(PhysReg.first);
2376
2377 // If this is an expanded reference, add the rest of the regs to Regs.
2378 if (NumRegs != 1) {
Chris Lattner864635a2006-02-22 22:37:12 +00002379 TargetRegisterClass::iterator I = PhysReg.second->begin();
2380 TargetRegisterClass::iterator E = PhysReg.second->end();
2381 for (; *I != PhysReg.first; ++I)
2382 assert(I != E && "Didn't find reg!");
2383
2384 // Already added the first reg.
2385 --NumRegs; ++I;
2386 for (; NumRegs; --NumRegs, ++I) {
2387 assert(I != E && "Ran out of registers to allocate!");
2388 Regs.push_back(*I);
2389 }
2390 }
2391 return RegsForValue(Regs, RegVT, ValueVT);
2392 }
2393
Chris Lattner2a821602006-11-02 01:41:49 +00002394 // Otherwise, if this was a reference to an LLVM register class, create vregs
2395 // for this reference.
2396 std::vector<unsigned> RegClassRegs;
2397 if (PhysReg.second) {
2398 // If this is an early clobber or tied register, our regalloc doesn't know
2399 // how to maintain the constraint. If it isn't, go ahead and create vreg
2400 // and let the regalloc do the right thing.
2401 if (!isOutReg || !isInReg) {
2402 if (VT == MVT::Other)
2403 ValueVT = *PhysReg.second->vt_begin();
2404 RegVT = *PhysReg.second->vt_begin();
2405
2406 // Create the appropriate number of virtual registers.
2407 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2408 for (; NumRegs; --NumRegs)
2409 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2410
2411 return RegsForValue(Regs, RegVT, ValueVT);
2412 }
2413
2414 // Otherwise, we can't allocate it. Let the code below figure out how to
2415 // maintain these constraints.
2416 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2417
2418 } else {
2419 // This is a reference to a register class that doesn't directly correspond
2420 // to an LLVM register class. Allocate NumRegs consecutive, available,
2421 // registers from the class.
2422 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2423 }
Chris Lattner864635a2006-02-22 22:37:12 +00002424
2425 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2426 MachineFunction &MF = *CurMBB->getParent();
2427 unsigned NumAllocated = 0;
2428 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2429 unsigned Reg = RegClassRegs[i];
2430 // See if this register is available.
2431 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2432 (isInReg && InputRegs.count(Reg))) { // Already used.
2433 // Make sure we find consecutive registers.
2434 NumAllocated = 0;
2435 continue;
2436 }
2437
2438 // Check to see if this register is allocatable (i.e. don't give out the
2439 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002440 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00002441 if (!RC) {
2442 // Make sure we find consecutive registers.
2443 NumAllocated = 0;
2444 continue;
2445 }
2446
2447 // Okay, this register is good, we can use it.
2448 ++NumAllocated;
2449
2450 // If we allocated enough consecutive
2451 if (NumAllocated == NumRegs) {
2452 unsigned RegStart = (i-NumAllocated)+1;
2453 unsigned RegEnd = i+1;
2454 // Mark all of the allocated registers used.
2455 for (unsigned i = RegStart; i != RegEnd; ++i) {
2456 unsigned Reg = RegClassRegs[i];
2457 Regs.push_back(Reg);
2458 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2459 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2460 }
2461
2462 return RegsForValue(Regs, *RC->vt_begin(), VT);
2463 }
2464 }
2465
2466 // Otherwise, we couldn't allocate enough registers for this.
2467 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00002468}
2469
Chris Lattner864635a2006-02-22 22:37:12 +00002470
Chris Lattnerce7518c2006-01-26 22:24:51 +00002471/// visitInlineAsm - Handle a call to an InlineAsm object.
2472///
2473void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2474 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2475
2476 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2477 MVT::Other);
2478
Chris Lattner2cc2f662006-02-01 01:28:23 +00002479 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002480 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00002481
2482 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2483 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2484 /// if it is a def of that register.
2485 std::vector<SDOperand> AsmNodeOperands;
2486 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2487 AsmNodeOperands.push_back(AsmStr);
2488
2489 SDOperand Chain = getRoot();
2490 SDOperand Flag;
2491
Chris Lattner4e4b5762006-02-01 18:59:47 +00002492 // We fully assign registers here at isel time. This is not optimal, but
2493 // should work. For register classes that correspond to LLVM classes, we
2494 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2495 // over the constraints, collecting fixed registers that we know we can't use.
2496 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002497 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002498 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2499 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2500 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner2223aea2006-02-02 00:25:23 +00002501
Chris Lattner1efa40f2006-02-22 00:56:39 +00002502 MVT::ValueType OpVT;
2503
2504 // Compute the value type for each operand and add it to ConstraintVTs.
2505 switch (Constraints[i].Type) {
2506 case InlineAsm::isOutput:
2507 if (!Constraints[i].isIndirectOutput) {
2508 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2509 OpVT = TLI.getValueType(I.getType());
2510 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002511 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002512 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2513 OpNum++; // Consumes a call operand.
2514 }
2515 break;
2516 case InlineAsm::isInput:
2517 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2518 OpNum++; // Consumes a call operand.
2519 break;
2520 case InlineAsm::isClobber:
2521 OpVT = MVT::Other;
2522 break;
2523 }
2524
2525 ConstraintVTs.push_back(OpVT);
2526
Chris Lattner864635a2006-02-22 22:37:12 +00002527 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2528 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00002529
Chris Lattner864635a2006-02-22 22:37:12 +00002530 // Build a list of regs that this operand uses. This always has a single
2531 // element for promoted/expanded operands.
2532 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2533 false, false,
2534 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00002535
2536 switch (Constraints[i].Type) {
2537 case InlineAsm::isOutput:
2538 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002539 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002540 // If this is an early-clobber output, it cannot be assigned to the same
2541 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00002542 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00002543 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002544 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002545 case InlineAsm::isInput:
2546 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002547 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00002548 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002549 case InlineAsm::isClobber:
2550 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00002551 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2552 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002553 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002554 }
2555 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00002556
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002557 // Loop over all of the inputs, copying the operand values into the
2558 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00002559 RegsForValue RetValRegs;
2560 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002561 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002562
Chris Lattner6656dd12006-01-31 02:03:41 +00002563 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00002564 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2565 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner1efa40f2006-02-22 00:56:39 +00002566
Chris Lattner2cc2f662006-02-01 01:28:23 +00002567 switch (Constraints[i].Type) {
2568 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00002569 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2570 if (ConstraintCode.size() == 1) // not a physreg name.
2571 CTy = TLI.getConstraintType(ConstraintCode[0]);
2572
2573 if (CTy == TargetLowering::C_Memory) {
2574 // Memory output.
2575 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2576
2577 // Check that the operand (the address to store to) isn't a float.
2578 if (!MVT::isInteger(InOperandVal.getValueType()))
2579 assert(0 && "MATCH FAIL!");
2580
2581 if (!Constraints[i].isIndirectOutput)
2582 assert(0 && "MATCH FAIL!");
2583
2584 OpNum++; // Consumes a call operand.
2585
2586 // Extend/truncate to the right pointer type if needed.
2587 MVT::ValueType PtrType = TLI.getPointerTy();
2588 if (InOperandVal.getValueType() < PtrType)
2589 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2590 else if (InOperandVal.getValueType() > PtrType)
2591 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2592
2593 // Add information to the INLINEASM node to know about this output.
2594 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2595 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2596 AsmNodeOperands.push_back(InOperandVal);
2597 break;
2598 }
2599
2600 // Otherwise, this is a register output.
2601 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2602
Chris Lattner864635a2006-02-22 22:37:12 +00002603 // If this is an early-clobber output, or if there is an input
2604 // constraint that matches this, we need to reserve the input register
2605 // so no other inputs allocate to it.
2606 bool UsesInputRegister = false;
2607 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2608 UsesInputRegister = true;
2609
2610 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00002611 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00002612 RegsForValue Regs =
2613 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2614 true, UsesInputRegister,
2615 OutputRegs, InputRegs);
Chris Lattnerd03f1582006-10-31 07:33:13 +00002616 if (Regs.Regs.empty()) {
2617 std::cerr << "Couldn't allocate output reg for contraint '"
2618 << ConstraintCode << "'!\n";
2619 exit(1);
2620 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00002621
Chris Lattner2cc2f662006-02-01 01:28:23 +00002622 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00002623 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00002624 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00002625 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00002626 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00002627 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002628 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2629 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00002630 OpNum++; // Consumes a call operand.
2631 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002632
2633 // Add information to the INLINEASM node to know that this register is
2634 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002635 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002636 break;
2637 }
2638 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00002639 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00002640 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00002641
Chris Lattner2223aea2006-02-02 00:25:23 +00002642 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2643 // If this is required to match an output register we have already set,
2644 // just use its register.
2645 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00002646
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002647 // Scan until we find the definition we already emitted of this operand.
2648 // When we find it, create a RegsForValue operand.
2649 unsigned CurOp = 2; // The first operand.
2650 for (; OperandNo; --OperandNo) {
2651 // Advance to the next operand.
2652 unsigned NumOps =
2653 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00002654 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2655 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002656 "Skipped past definitions?");
2657 CurOp += (NumOps>>3)+1;
2658 }
2659
2660 unsigned NumOps =
2661 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2662 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2663 "Skipped past definitions?");
2664
2665 // Add NumOps>>3 registers to MatchedRegs.
2666 RegsForValue MatchedRegs;
2667 MatchedRegs.ValueVT = InOperandVal.getValueType();
2668 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2669 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2670 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2671 MatchedRegs.Regs.push_back(Reg);
2672 }
2673
2674 // Use the produced MatchedRegs object to
Evan Chenga8441262006-06-15 08:11:54 +00002675 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2676 TLI.getPointerTy());
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002677 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002678 break;
Chris Lattner2223aea2006-02-02 00:25:23 +00002679 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002680
2681 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2682 if (ConstraintCode.size() == 1) // not a physreg name.
2683 CTy = TLI.getConstraintType(ConstraintCode[0]);
2684
2685 if (CTy == TargetLowering::C_Other) {
Chris Lattner53069fb2006-10-31 19:41:18 +00002686 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2687 ConstraintCode[0], DAG);
2688 if (!InOperandVal.Val) {
2689 std::cerr << "Invalid operand for inline asm constraint '"
2690 << ConstraintCode << "'!\n";
2691 exit(1);
2692 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002693
2694 // Add information to the INLINEASM node to know about this input.
2695 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2696 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2697 AsmNodeOperands.push_back(InOperandVal);
2698 break;
2699 } else if (CTy == TargetLowering::C_Memory) {
2700 // Memory input.
2701
2702 // Check that the operand isn't a float.
2703 if (!MVT::isInteger(InOperandVal.getValueType()))
2704 assert(0 && "MATCH FAIL!");
2705
2706 // Extend/truncate to the right pointer type if needed.
2707 MVT::ValueType PtrType = TLI.getPointerTy();
2708 if (InOperandVal.getValueType() < PtrType)
2709 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2710 else if (InOperandVal.getValueType() > PtrType)
2711 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2712
2713 // Add information to the INLINEASM node to know about this input.
2714 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2715 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2716 AsmNodeOperands.push_back(InOperandVal);
2717 break;
2718 }
2719
2720 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2721
2722 // Copy the input into the appropriate registers.
2723 RegsForValue InRegs =
2724 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2725 false, true, OutputRegs, InputRegs);
2726 // FIXME: should be match fail.
2727 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2728
Evan Chenga8441262006-06-15 08:11:54 +00002729 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002730
2731 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002732 break;
2733 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002734 case InlineAsm::isClobber: {
2735 RegsForValue ClobberedRegs =
2736 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2737 OutputRegs, InputRegs);
2738 // Add the clobbered value to the operand list, so that the register
2739 // allocator is aware that the physreg got clobbered.
2740 if (!ClobberedRegs.Regs.empty())
2741 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002742 break;
2743 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002744 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002745 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002746
2747 // Finish up input operands.
2748 AsmNodeOperands[0] = Chain;
2749 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2750
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002751 Chain = DAG.getNode(ISD::INLINEASM,
2752 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002753 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002754 Flag = Chain.getValue(1);
2755
Chris Lattner6656dd12006-01-31 02:03:41 +00002756 // If this asm returns a register value, copy the result from that register
2757 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00002758 if (!RetValRegs.Regs.empty())
2759 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00002760
Chris Lattner6656dd12006-01-31 02:03:41 +00002761 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2762
2763 // Process indirect outputs, first output all of the flagged copies out of
2764 // physregs.
2765 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00002766 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00002767 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00002768 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2769 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00002770 }
2771
2772 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002773 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00002774 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Cheng786225a2006-10-05 23:01:46 +00002775 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00002776 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00002777 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00002778 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002779 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2780 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002781 DAG.setRoot(Chain);
2782}
2783
2784
Chris Lattner1c08c712005-01-07 07:47:53 +00002785void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2786 SDOperand Src = getValue(I.getOperand(0));
2787
2788 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002789
2790 if (IntPtr < Src.getValueType())
2791 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2792 else if (IntPtr > Src.getValueType())
2793 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00002794
2795 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00002796 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00002797 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2798 Src, getIntPtrConstant(ElementSize));
2799
2800 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Andersona69571c2006-05-03 01:29:57 +00002801 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00002802
2803 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00002804 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002805 DAG.getExternalSymbol("malloc", IntPtr),
2806 Args, DAG);
2807 setValue(&I, Result.first); // Pointers always fit in registers
2808 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002809}
2810
2811void SelectionDAGLowering::visitFree(FreeInst &I) {
2812 std::vector<std::pair<SDOperand, const Type*> > Args;
2813 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Andersona69571c2006-05-03 01:29:57 +00002814 TLI.getTargetData()->getIntPtrType()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002815 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00002816 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00002817 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002818 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2819 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002820}
2821
Chris Lattner025c39b2005-08-26 20:54:47 +00002822// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2823// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2824// instructions are special in various ways, which require special support to
2825// insert. The specified MachineInstr is created but not inserted into any
2826// basic blocks, and the scheduler passes ownership of it to this method.
2827MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2828 MachineBasicBlock *MBB) {
2829 std::cerr << "If a target marks an instruction with "
2830 "'usesCustomDAGSchedInserter', it must implement "
2831 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2832 abort();
2833 return 0;
2834}
2835
Chris Lattner39ae3622005-01-09 00:00:49 +00002836void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002837 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2838 getValue(I.getOperand(1)),
2839 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00002840}
2841
2842void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002843 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2844 getValue(I.getOperand(0)),
2845 DAG.getSrcValue(I.getOperand(0)));
2846 setValue(&I, V);
2847 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002848}
2849
2850void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002851 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2852 getValue(I.getOperand(1)),
2853 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002854}
2855
2856void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002857 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2858 getValue(I.getOperand(1)),
2859 getValue(I.getOperand(2)),
2860 DAG.getSrcValue(I.getOperand(1)),
2861 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002862}
2863
Chris Lattnerfdfded52006-04-12 16:20:43 +00002864/// TargetLowering::LowerArguments - This is the default LowerArguments
2865/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002866/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2867/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00002868std::vector<SDOperand>
2869TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2870 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2871 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002872 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00002873 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2874 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2875
2876 // Add one result value for each formal argument.
2877 std::vector<MVT::ValueType> RetVals;
2878 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2879 MVT::ValueType VT = getValueType(I->getType());
2880
2881 switch (getTypeAction(VT)) {
2882 default: assert(0 && "Unknown type action!");
2883 case Legal:
2884 RetVals.push_back(VT);
2885 break;
2886 case Promote:
2887 RetVals.push_back(getTypeToTransformTo(VT));
2888 break;
2889 case Expand:
2890 if (VT != MVT::Vector) {
2891 // If this is a large integer, it needs to be broken up into small
2892 // integers. Figure out what the destination type is and how many small
2893 // integers it turns into.
2894 MVT::ValueType NVT = getTypeToTransformTo(VT);
2895 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2896 for (unsigned i = 0; i != NumVals; ++i)
2897 RetVals.push_back(NVT);
2898 } else {
2899 // Otherwise, this is a vector type. We only support legal vectors
2900 // right now.
2901 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2902 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002903
Chris Lattnerfdfded52006-04-12 16:20:43 +00002904 // Figure out if there is a Packed type corresponding to this Vector
2905 // type. If so, convert to the packed type.
2906 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2907 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2908 RetVals.push_back(TVT);
2909 } else {
2910 assert(0 && "Don't support illegal by-val vector arguments yet!");
2911 }
2912 }
2913 break;
2914 }
2915 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00002916
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002917 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00002918
2919 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002920 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2921 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002922 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002923
2924 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002925
2926 // Set up the return result vector.
2927 Ops.clear();
2928 unsigned i = 0;
2929 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2930 MVT::ValueType VT = getValueType(I->getType());
2931
2932 switch (getTypeAction(VT)) {
2933 default: assert(0 && "Unknown type action!");
2934 case Legal:
2935 Ops.push_back(SDOperand(Result, i++));
2936 break;
2937 case Promote: {
2938 SDOperand Op(Result, i++);
2939 if (MVT::isInteger(VT)) {
2940 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2941 : ISD::AssertZext;
2942 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2943 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2944 } else {
2945 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2946 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2947 }
2948 Ops.push_back(Op);
2949 break;
2950 }
2951 case Expand:
2952 if (VT != MVT::Vector) {
2953 // If this is a large integer, it needs to be reassembled from small
2954 // integers. Figure out what the source elt type is and how many small
2955 // integers it is.
2956 MVT::ValueType NVT = getTypeToTransformTo(VT);
2957 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2958 if (NumVals == 2) {
2959 SDOperand Lo = SDOperand(Result, i++);
2960 SDOperand Hi = SDOperand(Result, i++);
2961
2962 if (!isLittleEndian())
2963 std::swap(Lo, Hi);
2964
2965 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2966 } else {
2967 // Value scalarized into many values. Unimp for now.
2968 assert(0 && "Cannot expand i64 -> i16 yet!");
2969 }
2970 } else {
2971 // Otherwise, this is a vector type. We only support legal vectors
2972 // right now.
Evan Cheng020c41f2006-04-28 05:25:15 +00002973 const PackedType *PTy = cast<PackedType>(I->getType());
2974 unsigned NumElems = PTy->getNumElements();
2975 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002976
Chris Lattnerfdfded52006-04-12 16:20:43 +00002977 // Figure out if there is a Packed type corresponding to this Vector
2978 // type. If so, convert to the packed type.
2979 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00002980 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00002981 SDOperand N = SDOperand(Result, i++);
2982 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00002983 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2984 DAG.getConstant(NumElems, MVT::i32),
2985 DAG.getValueType(getValueType(EltTy)));
2986 Ops.push_back(N);
2987 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002988 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00002989 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00002990 }
2991 }
2992 break;
2993 }
2994 }
2995 return Ops;
2996}
2997
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002998
2999/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3000/// implementation, which just inserts an ISD::CALL node, which is later custom
3001/// lowered by the target to something concrete. FIXME: When all targets are
3002/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3003std::pair<SDOperand, SDOperand>
3004TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
3005 unsigned CallingConv, bool isTailCall,
3006 SDOperand Callee,
3007 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00003008 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003009 Ops.push_back(Chain); // Op#0 - Chain
3010 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3011 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3012 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3013 Ops.push_back(Callee);
3014
3015 // Handle all of the outgoing arguments.
3016 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
3017 MVT::ValueType VT = getValueType(Args[i].second);
3018 SDOperand Op = Args[i].first;
Evan Chengf6d62c22006-05-25 00:55:32 +00003019 bool isSigned = Args[i].second->isSigned();
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003020 switch (getTypeAction(VT)) {
3021 default: assert(0 && "Unknown type action!");
3022 case Legal:
3023 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00003024 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003025 break;
3026 case Promote:
3027 if (MVT::isInteger(VT)) {
Evan Chengf6d62c22006-05-25 00:55:32 +00003028 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003029 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3030 } else {
3031 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3032 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3033 }
3034 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00003035 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003036 break;
3037 case Expand:
3038 if (VT != MVT::Vector) {
3039 // If this is a large integer, it needs to be broken down into small
3040 // integers. Figure out what the source elt type is and how many small
3041 // integers it is.
3042 MVT::ValueType NVT = getTypeToTransformTo(VT);
3043 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
3044 if (NumVals == 2) {
3045 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
3046 DAG.getConstant(0, getPointerTy()));
3047 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
3048 DAG.getConstant(1, getPointerTy()));
3049 if (!isLittleEndian())
3050 std::swap(Lo, Hi);
3051
3052 Ops.push_back(Lo);
Evan Chengd61c4822006-05-26 23:13:20 +00003053 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003054 Ops.push_back(Hi);
Evan Chengd61c4822006-05-26 23:13:20 +00003055 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003056 } else {
3057 // Value scalarized into many values. Unimp for now.
3058 assert(0 && "Cannot expand i64 -> i16 yet!");
3059 }
3060 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003061 // Otherwise, this is a vector type. We only support legal vectors
3062 // right now.
3063 const PackedType *PTy = cast<PackedType>(Args[i].second);
3064 unsigned NumElems = PTy->getNumElements();
3065 const Type *EltTy = PTy->getElementType();
3066
3067 // Figure out if there is a Packed type corresponding to this Vector
3068 // type. If so, convert to the packed type.
3069 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00003070 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3071 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
3072 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3073 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00003074 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00003075 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003076 assert(0 && "Don't support illegal by-val vector call args yet!");
3077 abort();
3078 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003079 }
3080 break;
3081 }
3082 }
3083
3084 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00003085 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003086
3087 if (RetTy != Type::VoidTy) {
3088 MVT::ValueType VT = getValueType(RetTy);
3089 switch (getTypeAction(VT)) {
3090 default: assert(0 && "Unknown type action!");
3091 case Legal:
3092 RetTys.push_back(VT);
3093 break;
3094 case Promote:
3095 RetTys.push_back(getTypeToTransformTo(VT));
3096 break;
3097 case Expand:
3098 if (VT != MVT::Vector) {
3099 // If this is a large integer, it needs to be reassembled from small
3100 // integers. Figure out what the source elt type is and how many small
3101 // integers it is.
3102 MVT::ValueType NVT = getTypeToTransformTo(VT);
3103 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
3104 for (unsigned i = 0; i != NumVals; ++i)
3105 RetTys.push_back(NVT);
3106 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003107 // Otherwise, this is a vector type. We only support legal vectors
3108 // right now.
3109 const PackedType *PTy = cast<PackedType>(RetTy);
3110 unsigned NumElems = PTy->getNumElements();
3111 const Type *EltTy = PTy->getElementType();
3112
3113 // Figure out if there is a Packed type corresponding to this Vector
3114 // type. If so, convert to the packed type.
3115 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3116 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3117 RetTys.push_back(TVT);
3118 } else {
3119 assert(0 && "Don't support illegal by-val vector call results yet!");
3120 abort();
3121 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003122 }
3123 }
3124 }
3125
3126 RetTys.push_back(MVT::Other); // Always has a chain.
3127
3128 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00003129 SDOperand Res = DAG.getNode(ISD::CALL,
3130 DAG.getVTList(&RetTys[0], RetTys.size()),
3131 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003132
3133 // This returns a pair of operands. The first element is the
3134 // return value for the function (if RetTy is not VoidTy). The second
3135 // element is the outgoing token chain.
3136 SDOperand ResVal;
3137 if (RetTys.size() != 1) {
3138 MVT::ValueType VT = getValueType(RetTy);
3139 if (RetTys.size() == 2) {
3140 ResVal = Res;
3141
3142 // If this value was promoted, truncate it down.
3143 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003144 if (VT == MVT::Vector) {
3145 // Insert a VBITCONVERT to convert from the packed result type to the
3146 // MVT::Vector type.
3147 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3148 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3149
3150 // Figure out if there is a Packed type corresponding to this Vector
3151 // type. If so, convert to the packed type.
3152 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3153 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003154 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3155 // "N x PTyElementVT" MVT::Vector type.
3156 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00003157 DAG.getConstant(NumElems, MVT::i32),
3158 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00003159 } else {
3160 abort();
3161 }
3162 } else if (MVT::isInteger(VT)) {
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003163 unsigned AssertOp = RetTy->isSigned() ?
3164 ISD::AssertSext : ISD::AssertZext;
3165 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3166 DAG.getValueType(VT));
3167 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3168 } else {
3169 assert(MVT::isFloatingPoint(VT));
3170 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
3171 }
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 Lattner39ae3622005-01-09 00:00:49 +00003187// It is always conservatively correct for llvm.returnaddress and
3188// llvm.frameaddress to return 0.
Chris Lattnerf4ec8172006-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 Lattner39ae3622005-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 Lattner1c08c712005-01-07 07:47:53 +00003196}
3197
Chris Lattner50381b62005-05-14 05:50:48 +00003198SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00003199 assert(0 && "LowerOperation not implemented for this target!");
3200 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00003201 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00003202}
3203
Nate Begeman0aed7842006-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 Lattner39ae3622005-01-09 00:00:49 +00003211void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003212 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner39ae3622005-01-09 00:00:49 +00003213 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00003214 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00003215 setValue(&I, Result.first);
3216 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003217}
3218
Evan Cheng74d0aa92006-02-15 21:59:04 +00003219/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00003220/// operand.
3221static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00003222 SelectionDAG &DAG) {
Evan Cheng1db92f92006-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 Cheng1db92f92006-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 Cheng1db92f92006-02-14 08:22:34 +00003243 }
3244
3245 return Value;
3246 }
3247}
3248
Evan Cheng74d0aa92006-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 Cheng74d0aa92006-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 Chenga5a57d62006-11-29 01:38:07 +00003260 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng74d0aa92006-02-15 21:59:04 +00003261 Offset += TLI.isLittleEndian() ? -1 : 1;
3262 }
3263 return DAG.getConstant(Val, VT);
3264}
3265
Evan Cheng1db92f92006-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 Chengc4f8eee2006-02-14 20:12:38 +00003273/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-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 Chengc4f8eee2006-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 Cheng1db92f92006-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 Cheng80e89d72006-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 Cheng1db92f92006-02-14 08:22:34 +00003304
Evan Cheng80e89d72006-02-14 09:11:59 +00003305 if (VT > LVT)
3306 VT = LVT;
3307
Evan Chengdea72452006-02-14 23:05:54 +00003308 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-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 Cheng1db92f92006-02-14 08:22:34 +00003313 VTSize >>= 1;
3314 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003315 assert(MVT::isInteger(VT));
3316
3317 if (++NumMemOps > Limit)
3318 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00003319 MemOps.push_back(VT);
3320 Size -= VTSize;
3321 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003322
3323 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00003324}
3325
Chris Lattner7041ee32005-01-11 05:56:49 +00003326void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-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 Cheng1db92f92006-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 Lattnerbd564bf2006-08-08 02:23:42 +00003339 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00003340 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00003341 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00003342 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00003343 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3344 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00003345 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-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 Chenga47876d2006-02-15 22:12:35 +00003350 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00003351 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00003352 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003353 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00003354 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00003355 Offset += VTSize;
3356 }
Evan Cheng1db92f92006-02-14 08:22:34 +00003357 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003358 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00003359 }
Evan Chengc080d6f2006-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 Chengcffbb512006-02-16 23:11:42 +00003364 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003365 GlobalAddressSDNode *G = NULL;
3366 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00003367 bool CopyFromStr = false;
Evan Cheng74d0aa92006-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 Chengcffbb512006-02-16 23:11:42 +00003375 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00003376 }
3377 if (G) {
3378 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengf3e486e2006-11-29 01:58:12 +00003379 if (GV && GV->isConstant()) {
Evan Cheng09371032006-03-10 23:52:03 +00003380 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00003381 if (!Str.empty()) {
3382 CopyFromStr = true;
3383 SrcOff += SrcDelta;
3384 }
3385 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00003386 }
3387
Evan Chengc080d6f2006-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 Cheng74d0aa92006-02-15 21:59:04 +00003391 SDOperand Value, Chain, Store;
3392
Evan Chengcffbb512006-02-16 23:11:42 +00003393 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003394 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3395 Chain = getRoot();
3396 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003397 DAG.getStore(Chain, Value,
3398 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003399 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003400 } else {
3401 Value = DAG.getLoad(VT, getRoot(),
3402 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00003403 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003404 Chain = Value.getValue(1);
3405 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003406 DAG.getStore(Chain, Value,
3407 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003408 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003409 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003410 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003411 SrcOff += VTSize;
3412 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00003413 }
3414 }
3415 break;
3416 }
3417 }
3418
3419 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003420 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3421 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00003422 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00003423 }
3424 }
3425
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003426 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00003427}
3428
Chris Lattner7041ee32005-01-11 05:56:49 +00003429//===----------------------------------------------------------------------===//
3430// SelectionDAGISel code
3431//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00003432
3433unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3434 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3435}
3436
Chris Lattner495a0b52005-08-17 06:37:43 +00003437void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00003438 // FIXME: we only modify the CFG to split critical edges. This
3439 // updates dom and loop info.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003440 AU.addRequired<AliasAnalysis>();
Chris Lattner495a0b52005-08-17 06:37:43 +00003441}
Chris Lattner1c08c712005-01-07 07:47:53 +00003442
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003443
Chris Lattner90323642006-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 Spencer3da59db2006-11-27 01:05:10 +00003483 CastInst::createInferredCast(CI->getOperand(0), CI->getType(), "",
3484 InsertPt);
Chris Lattner90323642006-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 Lattnerc88d8e92005-12-05 07:10:48 +00003499/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3500/// casting to the type of GEPI.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003501static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3502 Instruction *GEPI, Value *Ptr,
3503 Value *PtrOffset) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003504 if (V) return V; // Already computed.
3505
Reid Spencer3da59db2006-11-27 01:05:10 +00003506 // Figure out the insertion point
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003507 BasicBlock::iterator InsertPt;
3508 if (BB == GEPI->getParent()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003509 // If GEP is already inserted into BB, insert right after the GEP.
Chris Lattnerc88d8e92005-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 Lattnerc78b0b72005-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 Spencer3da59db2006-11-27 01:05:10 +00003523 Ptr = CastInst::createInferredCast(CI->getOperand(0), CI->getType(), "",
3524 InsertPt);
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003525
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003526 // Add the offset, cast it to the right type.
3527 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Reid Spencer3da59db2006-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 Lattnerc88d8e92005-12-05 07:10:48 +00003531}
3532
Chris Lattner90323642006-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 Lattnerf0df8822006-05-06 09:10:37 +00003543 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner90323642006-05-05 21:17:49 +00003544 while (!RepPtr->use_empty()) {
3545 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7e598092006-05-05 01:04:50 +00003546
Reid Spencer3da59db2006-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 Lattner90323642006-05-05 21:17:49 +00003550 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7e598092006-05-05 01:04:50 +00003551
Chris Lattner90323642006-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 Lattner7e598092006-05-05 01:04:50 +00003556 }
3557
Chris Lattner90323642006-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 Lattnerf0df8822006-05-06 09:10:37 +00003560 Instruction *NewVal;
Chris Lattner90323642006-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 Lattnerf0df8822006-05-06 09:10:37 +00003573 if (GEPI->getType() != RepPtr->getType()) {
3574 BasicBlock::iterator IP = NewVal;
3575 ++IP;
Reid Spencer3da59db2006-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 Lattnerf0df8822006-05-06 09:10:37 +00003578 }
Chris Lattner90323642006-05-05 21:17:49 +00003579 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7e598092006-05-05 01:04:50 +00003580 }
3581}
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003582
Chris Lattner90323642006-05-05 21:17:49 +00003583
Chris Lattnerc88d8e92005-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 Lattner90323642006-05-05 21:17:49 +00003590static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Andersona69571c2006-05-03 01:29:57 +00003591 const TargetData *TD) {
Chris Lattnerc88d8e92005-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 Lattner90323642006-05-05 21:17:49 +00003603 if (!isUsedOutsideDefBB) return false;
Chris Lattnerc88d8e92005-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 Lattner90323642006-05-05 21:17:49 +00003608 bool hasVariableIndex = false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003609 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3610 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner90323642006-05-05 21:17:49 +00003611 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003612 if (CI->getZExtValue()) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003613 hasConstantIndex = true;
3614 break;
3615 }
Chris Lattner90323642006-05-05 21:17:49 +00003616 } else {
3617 hasVariableIndex = true;
3618 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003619 }
Chris Lattner90323642006-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 Spencer3da59db2006-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 Lattner90323642006-05-05 21:17:49 +00003625 GEPI->getName(), GEPI);
3626 GEPI->replaceAllUsesWith(NC);
3627 GEPI->eraseFromParent();
3628 return true;
3629 }
3630
Chris Lattner3802c252005-12-11 09:05:13 +00003631 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner90323642006-05-05 21:17:49 +00003632 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3633 return false;
Chris Lattnerc88d8e92005-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 Andersona69571c2006-05-03 01:29:57 +00003638 const Type *UIntPtrTy = TD->getIntPtrType();
Reid Spencer3da59db2006-11-27 01:05:10 +00003639 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
Chris Lattnerc88d8e92005-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 Spencerb83eb642006-10-20 07:07:24 +00003646 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003647 if (Field)
Owen Andersona69571c2006-05-03 01:29:57 +00003648 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattnerc88d8e92005-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 Spencerb83eb642006-10-20 07:07:24 +00003655 if (CI->getZExtValue() == 0) continue;
3656 if (CI->getType()->isSigned())
3657 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003658 else
Reid Spencerb83eb642006-10-20 07:07:24 +00003659 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003660 continue;
3661 }
3662
3663 // Ptr = Ptr + Idx * ElementSize;
3664
3665 // Cast Idx to UIntPtrTy if needed.
Reid Spencer3da59db2006-11-27 01:05:10 +00003666 Idx = CastInst::createInferredCast(Idx, UIntPtrTy, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003667
Owen Andersona69571c2006-05-03 01:29:57 +00003668 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003669 // Mask off bits that should not be set.
3670 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003671 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003672
3673 // Multiply by the element size and add to the base.
3674 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3675 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3676 }
3677 }
3678
3679 // Make sure that the offset fits in uintptr_t.
3680 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003681 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003682
3683 // Okay, we have now emitted all of the variable index parts to the BB that
3684 // the GEP is defined in. Loop over all of the using instructions, inserting
3685 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003686 // instruction to use the newly computed value, making GEPI dead. When the
3687 // user is a load or store instruction address, we emit the add into the user
3688 // block, otherwise we use a canonical version right next to the gep (these
3689 // won't be foldable as addresses, so we might as well share the computation).
3690
Chris Lattnerf0df8822006-05-06 09:10:37 +00003691 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner90323642006-05-05 21:17:49 +00003692 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003693
3694 // Finally, the GEP is dead, remove it.
3695 GEPI->eraseFromParent();
Chris Lattner90323642006-05-05 21:17:49 +00003696
3697 return true;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003698}
3699
Chris Lattnerbad7f482006-10-28 19:22:10 +00003700
3701/// SplitEdgeNicely - Split the critical edge from TI to it's specified
3702/// successor if it will improve codegen. We only do this if the successor has
3703/// phi nodes (otherwise critical edges are ok). If there is already another
3704/// predecessor of the succ that is empty (and thus has no phi nodes), use it
3705/// instead of introducing a new block.
3706static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3707 BasicBlock *TIBB = TI->getParent();
3708 BasicBlock *Dest = TI->getSuccessor(SuccNum);
3709 assert(isa<PHINode>(Dest->begin()) &&
3710 "This should only be called if Dest has a PHI!");
3711
3712 /// TIPHIValues - This array is lazily computed to determine the values of
3713 /// PHIs in Dest that TI would provide.
3714 std::vector<Value*> TIPHIValues;
3715
3716 // Check to see if Dest has any blocks that can be used as a split edge for
3717 // this terminator.
3718 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3719 BasicBlock *Pred = *PI;
3720 // To be usable, the pred has to end with an uncond branch to the dest.
3721 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3722 if (!PredBr || !PredBr->isUnconditional() ||
3723 // Must be empty other than the branch.
3724 &Pred->front() != PredBr)
3725 continue;
3726
3727 // Finally, since we know that Dest has phi nodes in it, we have to make
3728 // sure that jumping to Pred will have the same affect as going to Dest in
3729 // terms of PHI values.
3730 PHINode *PN;
3731 unsigned PHINo = 0;
3732 bool FoundMatch = true;
3733 for (BasicBlock::iterator I = Dest->begin();
3734 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3735 if (PHINo == TIPHIValues.size())
3736 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3737
3738 // If the PHI entry doesn't work, we can't use this pred.
3739 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3740 FoundMatch = false;
3741 break;
3742 }
3743 }
3744
3745 // If we found a workable predecessor, change TI to branch to Succ.
3746 if (FoundMatch) {
3747 Dest->removePredecessor(TIBB);
3748 TI->setSuccessor(SuccNum, Pred);
3749 return;
3750 }
3751 }
3752
3753 SplitCriticalEdge(TI, SuccNum, P, true);
3754}
3755
3756
Chris Lattner1c08c712005-01-07 07:47:53 +00003757bool SelectionDAGISel::runOnFunction(Function &Fn) {
3758 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3759 RegMap = MF.getSSARegMap();
3760 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3761
Chris Lattner47e32e62006-10-28 17:04:37 +00003762 // First, split all critical edges.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003763 //
Chris Lattner7e598092006-05-05 01:04:50 +00003764 // In this pass we also look for GEP and cast instructions that are used
3765 // across basic blocks and rewrite them to improve basic-block-at-a-time
3766 // selection.
3767 //
Chris Lattner90323642006-05-05 21:17:49 +00003768 bool MadeChange = true;
3769 while (MadeChange) {
3770 MadeChange = false;
Chris Lattner36b708f2005-08-18 17:35:14 +00003771 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnerbad7f482006-10-28 19:22:10 +00003772 // Split all critical edges where the dest block has a PHI.
Chris Lattner47e32e62006-10-28 17:04:37 +00003773 TerminatorInst *BBTI = BB->getTerminator();
3774 if (BBTI->getNumSuccessors() > 1) {
3775 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbad7f482006-10-28 19:22:10 +00003776 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3777 isCriticalEdge(BBTI, i, true))
3778 SplitEdgeNicely(BBTI, i, this);
Chris Lattner47e32e62006-10-28 17:04:37 +00003779 }
3780
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003781
Chris Lattner57f9a432006-09-28 06:17:10 +00003782 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7e598092006-05-05 01:04:50 +00003783 Instruction *I = BBI++;
Chris Lattner3f7927c2006-11-29 01:12:32 +00003784
3785 if (CallInst *CI = dyn_cast<CallInst>(I)) {
3786 // If we found an inline asm expession, and if the target knows how to
3787 // lower it to normal LLVM code, do so now.
3788 if (isa<InlineAsm>(CI->getCalledValue()))
3789 if (const TargetAsmInfo *TAI =
3790 TLI.getTargetMachine().getTargetAsmInfo()) {
3791 if (TAI->ExpandInlineAsm(CI))
3792 BBI = BB->begin();
3793 }
3794 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner90323642006-05-05 21:17:49 +00003795 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7e598092006-05-05 01:04:50 +00003796 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerc970f062006-09-13 06:02:42 +00003797 // If the source of the cast is a constant, then this should have
3798 // already been constant folded. The only reason NOT to constant fold
3799 // it is if something (e.g. LSR) was careful to place the constant
3800 // evaluation in a block other than then one that uses it (e.g. to hoist
3801 // the address of globals out of a loop). If this is the case, we don't
3802 // want to forward-subst the cast.
3803 if (isa<Constant>(CI->getOperand(0)))
3804 continue;
3805
Chris Lattner7e598092006-05-05 01:04:50 +00003806 // If this is a noop copy, sink it into user blocks to reduce the number
3807 // of virtual registers that must be created and coallesced.
3808 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3809 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3810
3811 // This is an fp<->int conversion?
3812 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3813 continue;
3814
3815 // If this is an extension, it will be a zero or sign extension, which
3816 // isn't a noop.
3817 if (SrcVT < DstVT) continue;
3818
3819 // If these values will be promoted, find out what they will be promoted
3820 // to. This helps us consider truncates on PPC as noop copies when they
3821 // are.
3822 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3823 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3824 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3825 DstVT = TLI.getTypeToTransformTo(DstVT);
3826
3827 // If, after promotion, these are the same types, this is a noop copy.
3828 if (SrcVT == DstVT)
Chris Lattner90323642006-05-05 21:17:49 +00003829 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7e598092006-05-05 01:04:50 +00003830 }
3831 }
Chris Lattner36b708f2005-08-18 17:35:14 +00003832 }
Chris Lattner90323642006-05-05 21:17:49 +00003833 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003834
Chris Lattner1c08c712005-01-07 07:47:53 +00003835 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3836
3837 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3838 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00003839
Chris Lattner1c08c712005-01-07 07:47:53 +00003840 return true;
3841}
3842
Chris Lattner571e4342006-10-27 21:36:01 +00003843SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3844 unsigned Reg) {
3845 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00003846 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003847 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00003848 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003849
3850 // If this type is not legal, we must make sure to not create an invalid
3851 // register use.
3852 MVT::ValueType SrcVT = Op.getValueType();
3853 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003854 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00003855 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003856 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00003857 // Handle copies from generic vectors to registers.
3858 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3859 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3860 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003861
Chris Lattner70c2a612006-03-31 02:06:56 +00003862 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3863 // MVT::Vector type.
3864 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3865 DAG.getConstant(NE, MVT::i32),
3866 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00003867
Chris Lattner70c2a612006-03-31 02:06:56 +00003868 // Loop over all of the elements of the resultant vector,
3869 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3870 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003871 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00003872 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00003873 for (unsigned i = 0; i != NE; ++i) {
3874 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003875 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003876 if (PTyElementVT == PTyLegalElementVT) {
3877 // Elements are legal.
3878 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3879 } else if (PTyLegalElementVT > PTyElementVT) {
3880 // Elements are promoted.
3881 if (MVT::isFloatingPoint(PTyLegalElementVT))
3882 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3883 else
3884 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3885 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3886 } else {
3887 // Elements are expanded.
3888 // The src value is expanded into multiple registers.
3889 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003890 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003891 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003892 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003893 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3894 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3895 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00003896 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003897 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3898 &OutChains[0], OutChains.size());
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003899 } else if (SrcVT < DestVT) {
3900 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00003901 if (MVT::isFloatingPoint(SrcVT))
3902 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3903 else
Chris Lattnerfab08872005-09-02 00:19:37 +00003904 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00003905 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003906 } else {
3907 // The src value is expanded into multiple registers.
3908 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003909 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003910 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003911 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00003912 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003913 return DAG.getCopyToReg(Op, Reg+1, Hi);
3914 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003915}
3916
Chris Lattner068a81e2005-01-17 17:15:02 +00003917void SelectionDAGISel::
3918LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3919 std::vector<SDOperand> &UnorderedChains) {
3920 // If this is the entry block, emit arguments.
3921 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00003922 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00003923 SDOperand OldRoot = SDL.DAG.getRoot();
3924 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00003925
Chris Lattnerbf209482005-10-30 19:42:35 +00003926 unsigned a = 0;
3927 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3928 AI != E; ++AI, ++a)
3929 if (!AI->use_empty()) {
3930 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00003931
Chris Lattnerbf209482005-10-30 19:42:35 +00003932 // If this argument is live outside of the entry block, insert a copy from
3933 // whereever we got it to the vreg that other BB's will reference it as.
3934 if (FuncInfo.ValueMap.count(AI)) {
3935 SDOperand Copy =
Chris Lattner571e4342006-10-27 21:36:01 +00003936 SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
Chris Lattnerbf209482005-10-30 19:42:35 +00003937 UnorderedChains.push_back(Copy);
3938 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00003939 }
Chris Lattnerbf209482005-10-30 19:42:35 +00003940
Chris Lattnerbf209482005-10-30 19:42:35 +00003941 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00003942 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00003943 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00003944}
3945
Chris Lattner1c08c712005-01-07 07:47:53 +00003946void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3947 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00003948 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00003949 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00003950
3951 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00003952
Chris Lattnerbf209482005-10-30 19:42:35 +00003953 // Lower any arguments needed in this block if this is the entry block.
3954 if (LLVMBB == &LLVMBB->getParent()->front())
3955 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00003956
3957 BB = FuncInfo.MBBMap[LLVMBB];
3958 SDL.setCurrentBasicBlock(BB);
3959
3960 // Lower all of the non-terminator instructions.
3961 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3962 I != E; ++I)
3963 SDL.visit(*I);
Nate Begemanf15485a2006-03-27 01:32:24 +00003964
Chris Lattner1c08c712005-01-07 07:47:53 +00003965 // Ensure that all instructions which are used outside of their defining
3966 // blocks are available as virtual registers.
3967 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00003968 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00003969 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00003970 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00003971 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00003972 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00003973 }
3974
3975 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3976 // ensure constants are generated when needed. Remember the virtual registers
3977 // that need to be added to the Machine PHI nodes as input. We cannot just
3978 // directly add them, because expansion might result in multiple MBB's for one
3979 // BB. As such, the start of the BB might correspond to a different MBB than
3980 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00003981 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00003982 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00003983
3984 // Emit constants only once even if used by multiple PHI nodes.
3985 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003986
Chris Lattner8c494ab2006-10-27 23:50:33 +00003987 // Vector bool would be better, but vector<bool> is really slow.
3988 std::vector<unsigned char> SuccsHandled;
3989 if (TI->getNumSuccessors())
3990 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
3991
Chris Lattner1c08c712005-01-07 07:47:53 +00003992 // Check successor nodes PHI nodes that expect a constant to be available from
3993 // this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00003994 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3995 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003996 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00003997 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003998
Chris Lattner8c494ab2006-10-27 23:50:33 +00003999 // If this terminator has multiple identical successors (common for
4000 // switches), only handle each succ once.
4001 unsigned SuccMBBNo = SuccMBB->getNumber();
4002 if (SuccsHandled[SuccMBBNo]) continue;
4003 SuccsHandled[SuccMBBNo] = true;
4004
4005 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004006 PHINode *PN;
4007
4008 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4009 // nodes and Machine PHI nodes, but the incoming operands have not been
4010 // emitted yet.
4011 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004012 (PN = dyn_cast<PHINode>(I)); ++I) {
4013 // Ignore dead phi's.
4014 if (PN->use_empty()) continue;
4015
4016 unsigned Reg;
4017 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004018
Chris Lattner8c494ab2006-10-27 23:50:33 +00004019 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4020 unsigned &RegOut = ConstantsOut[C];
4021 if (RegOut == 0) {
4022 RegOut = FuncInfo.CreateRegForValue(C);
4023 UnorderedChains.push_back(
4024 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00004025 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004026 Reg = RegOut;
4027 } else {
4028 Reg = FuncInfo.ValueMap[PHIOp];
4029 if (Reg == 0) {
4030 assert(isa<AllocaInst>(PHIOp) &&
4031 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4032 "Didn't codegen value into a register!??");
4033 Reg = FuncInfo.CreateRegForValue(PHIOp);
4034 UnorderedChains.push_back(
4035 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00004036 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004037 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004038
4039 // Remember that this register needs to added to the machine PHI node as
4040 // the input for this MBB.
4041 MVT::ValueType VT = TLI.getValueType(PN->getType());
4042 unsigned NumElements;
4043 if (VT != MVT::Vector)
4044 NumElements = TLI.getNumElements(VT);
4045 else {
4046 MVT::ValueType VT1,VT2;
4047 NumElements =
4048 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
4049 VT1, VT2);
4050 }
4051 for (unsigned i = 0, e = NumElements; i != e; ++i)
4052 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4053 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004054 }
4055 ConstantsOut.clear();
4056
Chris Lattnerddb870b2005-01-13 17:59:43 +00004057 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00004058 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00004059 SDOperand Root = SDL.getRoot();
4060 if (Root.getOpcode() != ISD::EntryToken) {
4061 unsigned i = 0, e = UnorderedChains.size();
4062 for (; i != e; ++i) {
4063 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4064 if (UnorderedChains[i].Val->getOperand(0) == Root)
4065 break; // Don't add the root if we already indirectly depend on it.
4066 }
4067
4068 if (i == e)
4069 UnorderedChains.push_back(Root);
4070 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004071 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4072 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00004073 }
4074
Chris Lattner1c08c712005-01-07 07:47:53 +00004075 // Lower the terminator after the copies are emitted.
4076 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004077
Nate Begemanf15485a2006-03-27 01:32:24 +00004078 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004079 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004080 SwitchCases.clear();
4081 SwitchCases = SDL.SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +00004082 JT = SDL.JT;
Nate Begemanf15485a2006-03-27 01:32:24 +00004083
Chris Lattnera651cf62005-01-17 19:43:36 +00004084 // Make sure the root of the DAG is up-to-date.
4085 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00004086}
4087
Nate Begemanf15485a2006-03-27 01:32:24 +00004088void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004089 // Get alias analysis for load/store combining.
4090 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4091
Chris Lattneraf21d552005-10-10 16:47:10 +00004092 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004093 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004094
Chris Lattner1c08c712005-01-07 07:47:53 +00004095 DEBUG(std::cerr << "Lowered selection DAG:\n");
4096 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004097
Chris Lattner1c08c712005-01-07 07:47:53 +00004098 // Second step, hack on the DAG until it only uses operations and types that
4099 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00004100 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004101
Chris Lattner1c08c712005-01-07 07:47:53 +00004102 DEBUG(std::cerr << "Legalized selection DAG:\n");
4103 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004104
Chris Lattneraf21d552005-10-10 16:47:10 +00004105 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004106 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004107
Evan Chenga9c20912006-01-21 02:32:06 +00004108 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004109
Chris Lattnera33ef482005-03-30 01:10:47 +00004110 // Third, instruction select all of the operations to machine code, adding the
4111 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004112 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004113
Chris Lattner1c08c712005-01-07 07:47:53 +00004114 DEBUG(std::cerr << "Selected machine code:\n");
4115 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004116}
Chris Lattner1c08c712005-01-07 07:47:53 +00004117
Nate Begemanf15485a2006-03-27 01:32:24 +00004118void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4119 FunctionLoweringInfo &FuncInfo) {
4120 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4121 {
4122 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4123 CurDAG = &DAG;
4124
4125 // First step, lower LLVM code to some DAG. This DAG may use operations and
4126 // types that are not supported by the target.
4127 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4128
4129 // Second step, emit the lowered DAG as machine code.
4130 CodeGenAndEmitDAG(DAG);
4131 }
4132
Chris Lattnera33ef482005-03-30 01:10:47 +00004133 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004134 // PHI nodes in successors.
Nate Begeman37efe672006-04-22 18:53:45 +00004135 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004136 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4137 MachineInstr *PHI = PHINodesToUpdate[i].first;
4138 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4139 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00004140 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004141 PHI->addMachineBasicBlockOperand(BB);
4142 }
4143 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004144 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004145
Nate Begeman9453eea2006-04-23 06:26:20 +00004146 // If the JumpTable record is filled in, then we need to emit a jump table.
4147 // Updating the PHI nodes is tricky in this case, since we need to determine
4148 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman37efe672006-04-22 18:53:45 +00004149 if (JT.Reg) {
4150 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
4151 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4152 CurDAG = &SDAG;
4153 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman9453eea2006-04-23 06:26:20 +00004154 MachineBasicBlock *RangeBB = BB;
Nate Begeman37efe672006-04-22 18:53:45 +00004155 // Set the current basic block to the mbb we wish to insert the code into
4156 BB = JT.MBB;
4157 SDL.setCurrentBasicBlock(BB);
4158 // Emit the code
4159 SDL.visitJumpTable(JT);
4160 SDAG.setRoot(SDL.getRoot());
4161 CodeGenAndEmitDAG(SDAG);
4162 // Update PHI Nodes
4163 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4164 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4165 MachineBasicBlock *PHIBB = PHI->getParent();
4166 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4167 "This is not a machine PHI node that we are updating!");
Nate Begemanf4360a42006-05-03 03:48:02 +00004168 if (PHIBB == JT.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004169 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004170 PHI->addMachineBasicBlockOperand(RangeBB);
4171 }
4172 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004173 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004174 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004175 }
4176 }
4177 return;
4178 }
4179
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004180 // If the switch block involved a branch to one of the actual successors, we
4181 // need to update PHI nodes in that block.
4182 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4183 MachineInstr *PHI = PHINodesToUpdate[i].first;
4184 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4185 "This is not a machine PHI node that we are updating!");
4186 if (BB->isSuccessor(PHI->getParent())) {
4187 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4188 PHI->addMachineBasicBlockOperand(BB);
4189 }
4190 }
4191
Nate Begemanf15485a2006-03-27 01:32:24 +00004192 // If we generated any switch lowering information, build and codegen any
4193 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004194 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004195 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
4196 CurDAG = &SDAG;
4197 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004198
Nate Begemanf15485a2006-03-27 01:32:24 +00004199 // Set the current basic block to the mbb we wish to insert the code into
4200 BB = SwitchCases[i].ThisBB;
4201 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004202
Nate Begemanf15485a2006-03-27 01:32:24 +00004203 // Emit the code
4204 SDL.visitSwitchCase(SwitchCases[i]);
4205 SDAG.setRoot(SDL.getRoot());
4206 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004207
4208 // Handle any PHI nodes in successors of this chunk, as if we were coming
4209 // from the original BB before switch expansion. Note that PHI nodes can
4210 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4211 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004212 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004213 for (MachineBasicBlock::iterator Phi = BB->begin();
4214 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4215 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4216 for (unsigned pn = 0; ; ++pn) {
4217 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4218 if (PHINodesToUpdate[pn].first == Phi) {
4219 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4220 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4221 break;
4222 }
4223 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004224 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004225
4226 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004227 if (BB == SwitchCases[i].FalseBB)
4228 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004229
4230 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004231 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004232 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004233 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004234 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004235 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004236}
Evan Chenga9c20912006-01-21 02:32:06 +00004237
Jim Laskey13ec7022006-08-01 14:21:23 +00004238
Evan Chenga9c20912006-01-21 02:32:06 +00004239//===----------------------------------------------------------------------===//
4240/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4241/// target node in the graph.
4242void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4243 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004244
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004245 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004246
4247 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004248 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004249 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004250 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004251
Jim Laskey9ff542f2006-08-01 18:29:48 +00004252 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004253 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00004254 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004255}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004256
Chris Lattner03fc53c2006-03-06 00:22:00 +00004257
Jim Laskey9ff542f2006-08-01 18:29:48 +00004258HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4259 return new HazardRecognizer();
4260}
4261
Chris Lattner75548062006-10-11 03:58:02 +00004262//===----------------------------------------------------------------------===//
4263// Helper functions used by the generated instruction selector.
4264//===----------------------------------------------------------------------===//
4265// Calls to these methods are generated by tblgen.
4266
4267/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4268/// the dag combiner simplified the 255, we still want to match. RHS is the
4269/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4270/// specified in the .td file (e.g. 255).
4271bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4272 int64_t DesiredMaskS) {
4273 uint64_t ActualMask = RHS->getValue();
4274 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4275
4276 // If the actual mask exactly matches, success!
4277 if (ActualMask == DesiredMask)
4278 return true;
4279
4280 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4281 if (ActualMask & ~DesiredMask)
4282 return false;
4283
4284 // Otherwise, the DAG Combiner may have proven that the value coming in is
4285 // either already zero or is not demanded. Check for known zero input bits.
4286 uint64_t NeededMask = DesiredMask & ~ActualMask;
4287 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4288 return true;
4289
4290 // TODO: check to see if missing bits are just not demanded.
4291
4292 // Otherwise, this pattern doesn't match.
4293 return false;
4294}
4295
4296/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4297/// the dag combiner simplified the 255, we still want to match. RHS is the
4298/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4299/// specified in the .td file (e.g. 255).
4300bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4301 int64_t DesiredMaskS) {
4302 uint64_t ActualMask = RHS->getValue();
4303 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4304
4305 // If the actual mask exactly matches, success!
4306 if (ActualMask == DesiredMask)
4307 return true;
4308
4309 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4310 if (ActualMask & ~DesiredMask)
4311 return false;
4312
4313 // Otherwise, the DAG Combiner may have proven that the value coming in is
4314 // either already zero or is not demanded. Check for known zero input bits.
4315 uint64_t NeededMask = DesiredMask & ~ActualMask;
4316
4317 uint64_t KnownZero, KnownOne;
4318 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4319
4320 // If all the missing bits in the or are already known to be set, match!
4321 if ((NeededMask & KnownOne) == NeededMask)
4322 return true;
4323
4324 // TODO: check to see if missing bits are just not demanded.
4325
4326 // Otherwise, this pattern doesn't match.
4327 return false;
4328}
4329
Jim Laskey9ff542f2006-08-01 18:29:48 +00004330
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004331/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4332/// by tblgen. Others should not call it.
4333void SelectionDAGISel::
4334SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4335 std::vector<SDOperand> InOps;
4336 std::swap(InOps, Ops);
4337
4338 Ops.push_back(InOps[0]); // input chain.
4339 Ops.push_back(InOps[1]); // input asm string.
4340
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004341 unsigned i = 2, e = InOps.size();
4342 if (InOps[e-1].getValueType() == MVT::Flag)
4343 --e; // Don't process a flag operand if it is here.
4344
4345 while (i != e) {
4346 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4347 if ((Flags & 7) != 4 /*MEM*/) {
4348 // Just skip over this operand, copying the operands verbatim.
4349 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4350 i += (Flags >> 3) + 1;
4351 } else {
4352 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4353 // Otherwise, this is a memory operand. Ask the target to select it.
4354 std::vector<SDOperand> SelOps;
4355 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4356 std::cerr << "Could not match memory address. Inline asm failure!\n";
4357 exit(1);
4358 }
4359
4360 // Add this to the output node.
4361 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
4362 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4363 i += 2;
4364 }
4365 }
4366
4367 // Add the flag input back if present.
4368 if (e != InOps.size())
4369 Ops.push_back(InOps.back());
4370}