blob: 7efc03efb0258aaece9c4fdec7fcd33eccb5971e [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"
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +000027#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskeyb2efb852006-01-04 22:28:25 +000028#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman37efe672006-04-22 18:53:45 +000031#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000033#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000034#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000036#include "llvm/Target/MRegisterInfo.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 <map>
Chris Lattner4e4b5762006-02-01 18:59:47 +000048#include <set>
Chris Lattner1c08c712005-01-07 07:47:53 +000049#include <iostream>
Jeff Cohen7e881032006-02-24 02:52:40 +000050#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000051using namespace llvm;
52
Chris Lattnerda8abb02005-09-01 18:44:10 +000053#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000054static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000055ViewISelDAGs("view-isel-dags", cl::Hidden,
56 cl::desc("Pop up a window to show isel dags as they are selected"));
57static cl::opt<bool>
58ViewSchedDAGs("view-sched-dags", cl::Hidden,
59 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000060#else
Chris Lattner5e46a192006-04-02 03:07:27 +000061static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000062#endif
63
Jim Laskeyeb577ba2006-08-02 12:30:23 +000064
65//===---------------------------------------------------------------------===//
66///
67/// RegisterScheduler class - Track the registration of instruction schedulers.
68///
69//===---------------------------------------------------------------------===//
70MachinePassRegistry RegisterScheduler::Registry;
71
72//===---------------------------------------------------------------------===//
73///
74/// ISHeuristic command line option for instruction schedulers.
75///
76//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000077namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000078 cl::opt<RegisterScheduler::FunctionPassCtor, false,
79 RegisterPassParser<RegisterScheduler> >
Jim Laskey13ec7022006-08-01 14:21:23 +000080 ISHeuristic("sched",
Chris Lattner3700f902006-08-03 00:18:59 +000081 cl::init(&createDefaultScheduler),
Jim Laskey13ec7022006-08-01 14:21:23 +000082 cl::desc("Instruction schedulers available:"));
83
Jim Laskey9ff542f2006-08-01 18:29:48 +000084 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000085 defaultListDAGScheduler("default", " Best scheduler for the target",
86 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000087} // namespace
88
Chris Lattner864635a2006-02-22 22:37:12 +000089namespace {
90 /// RegsForValue - This struct represents the physical registers that a
91 /// particular value is assigned and the type information about the value.
92 /// This is needed because values can be promoted into larger registers and
93 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +000094 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner864635a2006-02-22 22:37:12 +000095 /// Regs - This list hold the register (for legal and promoted values)
96 /// or register set (for expanded values) that the value should be assigned
97 /// to.
98 std::vector<unsigned> Regs;
99
100 /// RegVT - The value type of each register.
101 ///
102 MVT::ValueType RegVT;
103
104 /// ValueVT - The value type of the LLVM value, which may be promoted from
105 /// RegVT or made from merging the two expanded parts.
106 MVT::ValueType ValueVT;
107
108 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
109
110 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
111 : RegVT(regvt), ValueVT(valuevt) {
112 Regs.push_back(Reg);
113 }
114 RegsForValue(const std::vector<unsigned> &regs,
115 MVT::ValueType regvt, MVT::ValueType valuevt)
116 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
117 }
118
119 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
120 /// this value and returns the result as a ValueVT value. This uses
121 /// Chain/Flag as the input and updates them for the output Chain/Flag.
122 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000123 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000124
125 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
126 /// specified value into the registers specified by this object. This uses
127 /// Chain/Flag as the input and updates them for the output Chain/Flag.
128 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +0000129 SDOperand &Chain, SDOperand &Flag,
130 MVT::ValueType PtrVT) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000131
132 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
133 /// operand list. This adds the code marker and includes the number of
134 /// values added into it.
135 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000136 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000137 };
138}
Evan Cheng4ef10862006-01-23 07:01:07 +0000139
Chris Lattner1c08c712005-01-07 07:47:53 +0000140namespace llvm {
141 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000142 /// createDefaultScheduler - This creates an instruction scheduler appropriate
143 /// for the target.
144 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
145 SelectionDAG *DAG,
146 MachineBasicBlock *BB) {
147 TargetLowering &TLI = IS->getTargetLowering();
148
149 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
150 return createTDListDAGScheduler(IS, DAG, BB);
151 } else {
152 assert(TLI.getSchedulingPreference() ==
153 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
154 return createBURRListDAGScheduler(IS, DAG, BB);
155 }
156 }
157
158
159 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000160 /// FunctionLoweringInfo - This contains information that is global to a
161 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000162 class FunctionLoweringInfo {
163 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000164 TargetLowering &TLI;
165 Function &Fn;
166 MachineFunction &MF;
167 SSARegMap *RegMap;
168
169 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
170
171 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
172 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
173
174 /// ValueMap - Since we emit code for the function a basic block at a time,
175 /// we must remember which virtual registers hold the values for
176 /// cross-basic-block values.
177 std::map<const Value*, unsigned> ValueMap;
178
179 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
180 /// the entry block. This allows the allocas to be efficiently referenced
181 /// anywhere in the function.
182 std::map<const AllocaInst*, int> StaticAllocaMap;
183
184 unsigned MakeReg(MVT::ValueType VT) {
185 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
186 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000187
Chris Lattner3c384492006-03-16 19:51:18 +0000188 unsigned CreateRegForValue(const Value *V);
189
Chris Lattner1c08c712005-01-07 07:47:53 +0000190 unsigned InitializeRegForValue(const Value *V) {
191 unsigned &R = ValueMap[V];
192 assert(R == 0 && "Already initialized this value register!");
193 return R = CreateRegForValue(V);
194 }
195 };
196}
197
198/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000199/// PHI nodes or outside of the basic block that defines it, or used by a
200/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000201static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
202 if (isa<PHINode>(I)) return true;
203 BasicBlock *BB = I->getParent();
204 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000205 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
206 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000207 return true;
208 return false;
209}
210
Chris Lattnerbf209482005-10-30 19:42:35 +0000211/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000212/// entry block, return true. This includes arguments used by switches, since
213/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000214static bool isOnlyUsedInEntryBlock(Argument *A) {
215 BasicBlock *Entry = A->getParent()->begin();
216 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000217 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000218 return false; // Use not in entry block.
219 return true;
220}
221
Chris Lattner1c08c712005-01-07 07:47:53 +0000222FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000223 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000224 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
225
Chris Lattnerbf209482005-10-30 19:42:35 +0000226 // Create a vreg for each argument register that is not dead and is used
227 // outside of the entry block for the function.
228 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
229 AI != E; ++AI)
230 if (!isOnlyUsedInEntryBlock(AI))
231 InitializeRegForValue(AI);
232
Chris Lattner1c08c712005-01-07 07:47:53 +0000233 // Initialize the mapping of values to registers. This is only set up for
234 // instruction values that are used outside of the block that defines
235 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000236 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000237 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
238 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000239 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000240 const Type *Ty = AI->getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +0000241 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000242 unsigned Align =
Owen Andersona69571c2006-05-03 01:29:57 +0000243 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000244 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000245
Reid Spencerb83eb642006-10-20 07:07:24 +0000246 // If the alignment of the value is smaller than the size of the
247 // value, and if the size of the value is particularly small
248 // (<= 8 bytes), round up to the size of the value for potentially
249 // better performance.
Chris Lattnera8217e32005-05-13 23:14:17 +0000250 //
251 // FIXME: This could be made better with a preferred alignment hook in
252 // TargetData. It serves primarily to 8-byte align doubles for X86.
253 if (Align < TySize && TySize <= 8) Align = TySize;
Reid Spencerb83eb642006-10-20 07:07:24 +0000254 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000255 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000256 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000257 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000258 }
259
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000260 for (; BB != EB; ++BB)
261 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000262 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
263 if (!isa<AllocaInst>(I) ||
264 !StaticAllocaMap.count(cast<AllocaInst>(I)))
265 InitializeRegForValue(I);
266
267 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
268 // also creates the initial PHI MachineInstrs, though none of the input
269 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000270 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000271 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
272 MBBMap[BB] = MBB;
273 MF.getBasicBlockList().push_back(MBB);
274
275 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
276 // appropriate.
277 PHINode *PN;
278 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000279 (PN = dyn_cast<PHINode>(I)); ++I)
280 if (!PN->use_empty()) {
Chris Lattner70c2a612006-03-31 02:06:56 +0000281 MVT::ValueType VT = TLI.getValueType(PN->getType());
282 unsigned NumElements;
283 if (VT != MVT::Vector)
284 NumElements = TLI.getNumElements(VT);
285 else {
286 MVT::ValueType VT1,VT2;
287 NumElements =
288 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
289 VT1, VT2);
290 }
Chris Lattnerf44fd882005-01-07 21:34:19 +0000291 unsigned PHIReg = ValueMap[PN];
292 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
293 for (unsigned i = 0; i != NumElements; ++i)
294 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
295 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000296 }
297}
298
Chris Lattner3c384492006-03-16 19:51:18 +0000299/// CreateRegForValue - Allocate the appropriate number of virtual registers of
300/// the correctly promoted or expanded types. Assign these registers
301/// consecutive vreg numbers and return the first assigned number.
302unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
303 MVT::ValueType VT = TLI.getValueType(V->getType());
304
305 // The number of multiples of registers that we need, to, e.g., split up
306 // a <2 x int64> -> 4 x i32 registers.
307 unsigned NumVectorRegs = 1;
308
309 // If this is a packed type, figure out what type it will decompose into
310 // and how many of the elements it will use.
311 if (VT == MVT::Vector) {
312 const PackedType *PTy = cast<PackedType>(V->getType());
313 unsigned NumElts = PTy->getNumElements();
314 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
315
316 // Divide the input until we get to a supported size. This will always
317 // end with a scalar if the target doesn't support vectors.
318 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
319 NumElts >>= 1;
320 NumVectorRegs <<= 1;
321 }
Chris Lattner6cb70042006-03-16 23:05:19 +0000322 if (NumElts == 1)
323 VT = EltTy;
324 else
325 VT = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000326 }
327
328 // The common case is that we will only create one register for this
329 // value. If we have that case, create and return the virtual register.
330 unsigned NV = TLI.getNumElements(VT);
331 if (NV == 1) {
332 // If we are promoting this value, pick the next largest supported type.
333 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
334 unsigned Reg = MakeReg(PromotedType);
335 // If this is a vector of supported or promoted types (e.g. 4 x i16),
336 // create all of the registers.
337 for (unsigned i = 1; i != NumVectorRegs; ++i)
338 MakeReg(PromotedType);
339 return Reg;
340 }
341
342 // If this value is represented with multiple target registers, make sure
343 // to create enough consecutive registers of the right (smaller) type.
344 unsigned NT = VT-1; // Find the type to use.
345 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
346 --NT;
347
348 unsigned R = MakeReg((MVT::ValueType)NT);
349 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
350 MakeReg((MVT::ValueType)NT);
351 return R;
352}
Chris Lattner1c08c712005-01-07 07:47:53 +0000353
354//===----------------------------------------------------------------------===//
355/// SelectionDAGLowering - This is the common target-independent lowering
356/// implementation that is parameterized by a TargetLowering object.
357/// Also, targets can overload any lowering method.
358///
359namespace llvm {
360class SelectionDAGLowering {
361 MachineBasicBlock *CurMBB;
362
363 std::map<const Value*, SDOperand> NodeMap;
364
Chris Lattnerd3948112005-01-17 22:19:26 +0000365 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
366 /// them up and then emit token factor nodes when possible. This allows us to
367 /// get simple disambiguation between loads without worrying about alias
368 /// analysis.
369 std::vector<SDOperand> PendingLoads;
370
Nate Begemanf15485a2006-03-27 01:32:24 +0000371 /// Case - A pair of values to record the Value for a switch case, and the
372 /// case's target basic block.
373 typedef std::pair<Constant*, MachineBasicBlock*> Case;
374 typedef std::vector<Case>::iterator CaseItr;
375 typedef std::pair<CaseItr, CaseItr> CaseRange;
376
377 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
378 /// of conditional branches.
379 struct CaseRec {
380 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
381 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
382
383 /// CaseBB - The MBB in which to emit the compare and branch
384 MachineBasicBlock *CaseBB;
385 /// LT, GE - If nonzero, we know the current case value must be less-than or
386 /// greater-than-or-equal-to these Constants.
387 Constant *LT;
388 Constant *GE;
389 /// Range - A pair of iterators representing the range of case values to be
390 /// processed at this point in the binary search tree.
391 CaseRange Range;
392 };
393
394 /// The comparison function for sorting Case values.
395 struct CaseCmp {
396 bool operator () (const Case& C1, const Case& C2) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000397 if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
398 if (I1->getType()->isUnsigned())
399 return I1->getZExtValue() <
400 cast<const ConstantInt>(C2.first)->getZExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000401
Reid Spencerb83eb642006-10-20 07:07:24 +0000402 return cast<const ConstantInt>(C1.first)->getSExtValue() <
403 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000404 }
405 };
406
Chris Lattner1c08c712005-01-07 07:47:53 +0000407public:
408 // TLI - This is information that describes the available target features we
409 // need for lowering. This indicates when operations are unavailable,
410 // implemented with a libcall, etc.
411 TargetLowering &TLI;
412 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000413 const TargetData *TD;
Chris Lattner1c08c712005-01-07 07:47:53 +0000414
Nate Begemanf15485a2006-03-27 01:32:24 +0000415 /// SwitchCases - Vector of CaseBlock structures used to communicate
416 /// SwitchInst code generation information.
417 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +0000418 SelectionDAGISel::JumpTable JT;
Nate Begemanf15485a2006-03-27 01:32:24 +0000419
Chris Lattner1c08c712005-01-07 07:47:53 +0000420 /// FuncInfo - Information about the function as a whole.
421 ///
422 FunctionLoweringInfo &FuncInfo;
423
424 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000425 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000426 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman9453eea2006-04-23 06:26:20 +0000427 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000428 }
429
Chris Lattnera651cf62005-01-17 19:43:36 +0000430 /// getRoot - Return the current virtual root of the Selection DAG.
431 ///
432 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000433 if (PendingLoads.empty())
434 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000435
Chris Lattnerd3948112005-01-17 22:19:26 +0000436 if (PendingLoads.size() == 1) {
437 SDOperand Root = PendingLoads[0];
438 DAG.setRoot(Root);
439 PendingLoads.clear();
440 return Root;
441 }
442
443 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000444 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
445 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000446 PendingLoads.clear();
447 DAG.setRoot(Root);
448 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000449 }
450
Chris Lattner1c08c712005-01-07 07:47:53 +0000451 void visit(Instruction &I) { visit(I.getOpcode(), I); }
452
453 void visit(unsigned Opcode, User &I) {
454 switch (Opcode) {
455 default: assert(0 && "Unknown instruction type encountered!");
456 abort();
457 // Build the switch statement using the Instruction.def file.
458#define HANDLE_INST(NUM, OPCODE, CLASS) \
459 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
460#include "llvm/Instruction.def"
461 }
462 }
463
464 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
465
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000466 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000467 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000468 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000469
470 SDOperand getIntPtrConstant(uint64_t Val) {
471 return DAG.getConstant(Val, TLI.getPointerTy());
472 }
473
Chris Lattner199862b2006-03-16 19:57:50 +0000474 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000475
476 const SDOperand &setValue(const Value *V, SDOperand NewN) {
477 SDOperand &N = NodeMap[V];
478 assert(N.Val == 0 && "Already set a value for this node!");
479 return N = NewN;
480 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000481
Chris Lattner864635a2006-02-22 22:37:12 +0000482 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
483 MVT::ValueType VT,
484 bool OutReg, bool InReg,
485 std::set<unsigned> &OutputRegs,
486 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000487
Chris Lattner1c08c712005-01-07 07:47:53 +0000488 // Terminator instructions.
489 void visitRet(ReturnInst &I);
490 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000491 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000492 void visitUnreachable(UnreachableInst &I) { /* noop */ }
493
Nate Begemanf15485a2006-03-27 01:32:24 +0000494 // Helper for visitSwitch
495 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman37efe672006-04-22 18:53:45 +0000496 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemanf15485a2006-03-27 01:32:24 +0000497
Chris Lattner1c08c712005-01-07 07:47:53 +0000498 // These all get lowered before this pass.
Chris Lattner1c08c712005-01-07 07:47:53 +0000499 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
500 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
501
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000502 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000503 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000504 void visitAdd(User &I) {
505 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000506 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000507 void visitSub(User &I);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000508 void visitMul(User &I) {
509 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000510 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000511 void visitDiv(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000512 const Type *Ty = I.getType();
Evan Cheng3e1ce5a2006-03-03 07:01:07 +0000513 visitBinary(I,
514 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
515 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner1c08c712005-01-07 07:47:53 +0000516 }
517 void visitRem(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000518 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000519 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000520 }
Evan Cheng3e1ce5a2006-03-03 07:01:07 +0000521 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
522 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
523 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begemane21ea612005-11-18 07:42:56 +0000524 void visitShl(User &I) { visitShift(I, ISD::SHL); }
525 void visitShr(User &I) {
526 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000527 }
528
Evan Chengf6f95812006-05-23 06:40:47 +0000529 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
530 ISD::CondCode FPOpc);
531 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
532 ISD::SETOEQ); }
533 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
534 ISD::SETUNE); }
535 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
536 ISD::SETOLE); }
537 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
538 ISD::SETOGE); }
539 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
540 ISD::SETOLT); }
541 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
542 ISD::SETOGT); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000543
Chris Lattner2bbd8102006-03-29 00:11:43 +0000544 void visitExtractElement(User &I);
545 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000546 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000547
Chris Lattner1c08c712005-01-07 07:47:53 +0000548 void visitGetElementPtr(User &I);
549 void visitCast(User &I);
550 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000551
552 void visitMalloc(MallocInst &I);
553 void visitFree(FreeInst &I);
554 void visitAlloca(AllocaInst &I);
555 void visitLoad(LoadInst &I);
556 void visitStore(StoreInst &I);
557 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
558 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000559 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000560 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000561 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000562
Chris Lattner1c08c712005-01-07 07:47:53 +0000563 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000564 void visitVAArg(VAArgInst &I);
565 void visitVAEnd(CallInst &I);
566 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000567 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000568
Chris Lattner7041ee32005-01-11 05:56:49 +0000569 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000570
571 void visitUserOp1(Instruction &I) {
572 assert(0 && "UserOp1 should not exist at instruction selection time!");
573 abort();
574 }
575 void visitUserOp2(Instruction &I) {
576 assert(0 && "UserOp2 should not exist at instruction selection time!");
577 abort();
578 }
579};
580} // end namespace llvm
581
Chris Lattner199862b2006-03-16 19:57:50 +0000582SDOperand SelectionDAGLowering::getValue(const Value *V) {
583 SDOperand &N = NodeMap[V];
584 if (N.Val) return N;
585
586 const Type *VTy = V->getType();
587 MVT::ValueType VT = TLI.getValueType(VTy);
588 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
589 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
590 visit(CE->getOpcode(), *CE);
591 assert(N.Val && "visit didn't populate the ValueMap!");
592 return N;
593 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
594 return N = DAG.getGlobalAddress(GV, VT);
595 } else if (isa<ConstantPointerNull>(C)) {
596 return N = DAG.getConstant(0, TLI.getPointerTy());
597 } else if (isa<UndefValue>(C)) {
Chris Lattner23d564c2006-03-19 00:20:20 +0000598 if (!isa<PackedType>(VTy))
599 return N = DAG.getNode(ISD::UNDEF, VT);
600
Chris Lattnerb2827b02006-03-19 00:52:58 +0000601 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattner23d564c2006-03-19 00:20:20 +0000602 const PackedType *PTy = cast<PackedType>(VTy);
603 unsigned NumElements = PTy->getNumElements();
604 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
605
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000606 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000607 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
608
609 // Create a VConstant node with generic Vector type.
610 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
611 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000612 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
613 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000614 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
615 return N = DAG.getConstantFP(CFP->getValue(), VT);
616 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
617 unsigned NumElements = PTy->getNumElements();
618 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000619
620 // Now that we know the number and type of the elements, push a
621 // Constant or ConstantFP node onto the ops list for each element of
622 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000623 SmallVector<SDOperand, 8> Ops;
Chris Lattner199862b2006-03-16 19:57:50 +0000624 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000625 for (unsigned i = 0; i != NumElements; ++i)
626 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000627 } else {
628 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
629 SDOperand Op;
630 if (MVT::isFloatingPoint(PVT))
631 Op = DAG.getConstantFP(0, PVT);
632 else
633 Op = DAG.getConstant(0, PVT);
634 Ops.assign(NumElements, Op);
635 }
636
Chris Lattnerb2827b02006-03-19 00:52:58 +0000637 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000638 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
639 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000640 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000641 } else {
642 // Canonicalize all constant ints to be unsigned.
Reid Spencerb83eb642006-10-20 07:07:24 +0000643 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000644 }
645 }
646
647 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
648 std::map<const AllocaInst*, int>::iterator SI =
649 FuncInfo.StaticAllocaMap.find(AI);
650 if (SI != FuncInfo.StaticAllocaMap.end())
651 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
652 }
653
654 std::map<const Value*, unsigned>::const_iterator VMI =
655 FuncInfo.ValueMap.find(V);
656 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
657
658 unsigned InReg = VMI->second;
659
660 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000661 if (VT != MVT::Vector) {
662 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000663
Chris Lattner70c2a612006-03-31 02:06:56 +0000664 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
665 if (DestVT < VT) {
666 // Source must be expanded. This input value is actually coming from the
667 // register pair VMI->second and VMI->second+1.
668 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
669 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
670 } else if (DestVT > VT) { // Promotion case
Chris Lattner199862b2006-03-16 19:57:50 +0000671 if (MVT::isFloatingPoint(VT))
672 N = DAG.getNode(ISD::FP_ROUND, VT, N);
673 else
674 N = DAG.getNode(ISD::TRUNCATE, VT, N);
675 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000676 } else {
677 // Otherwise, if this is a vector, make it available as a generic vector
678 // here.
679 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Chris Lattner2e2ef952006-04-05 06:54:42 +0000680 const PackedType *PTy = cast<PackedType>(VTy);
681 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000682 PTyLegalElementVT);
683
684 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000685 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000686 if (PTyElementVT == PTyLegalElementVT) {
687 // If the value types are legal, just VBUILD the CopyFromReg nodes.
688 for (unsigned i = 0; i != NE; ++i)
689 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
690 PTyElementVT));
691 } else if (PTyElementVT < PTyLegalElementVT) {
692 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
693 for (unsigned i = 0; i != NE; ++i) {
694 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
695 PTyElementVT);
696 if (MVT::isFloatingPoint(PTyElementVT))
697 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
698 else
699 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
700 Ops.push_back(Op);
701 }
702 } else {
703 // If the register was expanded, use BUILD_PAIR.
704 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
705 for (unsigned i = 0; i != NE/2; ++i) {
706 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
707 PTyElementVT);
708 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
709 PTyElementVT);
710 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
711 }
712 }
713
714 Ops.push_back(DAG.getConstant(NE, MVT::i32));
715 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000716 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000717
718 // Finally, use a VBIT_CONVERT to make this available as the appropriate
719 // vector type.
720 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
721 DAG.getConstant(PTy->getNumElements(),
722 MVT::i32),
723 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000724 }
725
726 return N;
727}
728
729
Chris Lattner1c08c712005-01-07 07:47:53 +0000730void SelectionDAGLowering::visitRet(ReturnInst &I) {
731 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000732 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000733 return;
734 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000735 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000736 NewValues.push_back(getRoot());
737 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
738 SDOperand RetOp = getValue(I.getOperand(i));
Evan Cheng8e7d0562006-05-26 23:09:09 +0000739 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begemanee625572006-01-27 21:09:22 +0000740
741 // If this is an integer return value, we need to promote it ourselves to
742 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
743 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000744 // FIXME: C calling convention requires the return type to be promoted to
745 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000746 if (MVT::isInteger(RetOp.getValueType()) &&
747 RetOp.getValueType() < MVT::i64) {
748 MVT::ValueType TmpVT;
749 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
750 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
751 else
752 TmpVT = MVT::i32;
Chris Lattner1c08c712005-01-07 07:47:53 +0000753
Evan Cheng8e7d0562006-05-26 23:09:09 +0000754 if (isSigned)
Nate Begemanee625572006-01-27 21:09:22 +0000755 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
756 else
757 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
758 }
759 NewValues.push_back(RetOp);
Evan Cheng8e7d0562006-05-26 23:09:09 +0000760 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000761 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000762 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
763 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000764}
765
766void SelectionDAGLowering::visitBr(BranchInst &I) {
767 // Update machine-CFG edges.
768 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000769
770 // Figure out which block is immediately after the current one.
771 MachineBasicBlock *NextBlock = 0;
772 MachineFunction::iterator BBI = CurMBB;
773 if (++BBI != CurMBB->getParent()->end())
774 NextBlock = BBI;
775
776 if (I.isUnconditional()) {
777 // If this is not a fall-through branch, emit the branch.
778 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000779 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000780 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000781
Chris Lattner57ab6592006-10-24 17:57:59 +0000782 // Update machine-CFG edges.
783 CurMBB->addSuccessor(Succ0MBB);
784
785 return;
786 }
787
788 // If this condition is one of the special cases we handle, do special stuff
789 // now.
790 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +0000791 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner24525952006-10-24 18:07:37 +0000792
793 // Create a CaseBlock record representing this branch.
794 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, 0,
795 Succ0MBB, Succ1MBB, CurMBB);
796 // Use visitSwitchCase to actually insert the fast branch sequence for this
797 // cond branch.
798 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000799}
800
Nate Begemanf15485a2006-03-27 01:32:24 +0000801/// visitSwitchCase - Emits the necessary code to represent a single node in
802/// the binary search tree resulting from lowering a switch instruction.
803void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +0000804 SDOperand Cond;
805 SDOperand CondLHS = getValue(CB.CmpLHS);
806
807 // If the CaseBlock has both LHS/RHS comparisons, build the setcc now,
808 // otherwise, just use the LHS value as a bool comparison value.
809 if (CB.CmpRHS)
810 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
811 else
812 Cond = CondLHS;
Nate Begemanf15485a2006-03-27 01:32:24 +0000813
814 // Set NextBlock to be the MBB immediately after the current one, if any.
815 // This is used to avoid emitting unnecessary branches to the next block.
816 MachineBasicBlock *NextBlock = 0;
817 MachineFunction::iterator BBI = CurMBB;
818 if (++BBI != CurMBB->getParent()->end())
819 NextBlock = BBI;
820
821 // If the lhs block is the next block, invert the condition so that we can
822 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +0000823 if (CB.TrueBB == NextBlock) {
824 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +0000825 SDOperand True = DAG.getConstant(1, Cond.getValueType());
826 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
827 }
828 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +0000829 DAG.getBasicBlock(CB.TrueBB));
830 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +0000831 DAG.setRoot(BrCond);
832 else
833 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +0000834 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +0000835 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +0000836 CurMBB->addSuccessor(CB.TrueBB);
837 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +0000838}
839
Nate Begeman37efe672006-04-22 18:53:45 +0000840void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +0000841 // Emit the code for the jump table
842 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng8825a482006-08-01 01:03:13 +0000843 assert((PTy == MVT::i32 || PTy == MVT::i64) &&
844 "Jump table entries are 32-bit values");
Evan Cheng2ae5b872006-09-24 05:22:38 +0000845 bool isPIC = TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_;
Evan Cheng8825a482006-08-01 01:03:13 +0000846 // PIC jump table entries are 32-bit values.
Evan Cheng2ae5b872006-09-24 05:22:38 +0000847 unsigned EntrySize = isPIC ? 4 : MVT::getSizeInBits(PTy)/8;
Nate Begeman37efe672006-04-22 18:53:45 +0000848 SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
849 SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
Evan Cheng8825a482006-08-01 01:03:13 +0000850 DAG.getConstant(EntrySize, PTy));
Nate Begeman2f1ae882006-07-27 01:13:04 +0000851 SDOperand TAB = DAG.getJumpTable(JT.JTI,PTy);
852 SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, TAB);
Evan Cheng2ae5b872006-09-24 05:22:38 +0000853 SDOperand LD = DAG.getLoad(isPIC ? MVT::i32 : PTy, Copy.getValue(1), ADD,
Evan Cheng466685d2006-10-09 20:57:25 +0000854 NULL, 0);
Evan Cheng2ae5b872006-09-24 05:22:38 +0000855 if (isPIC) {
Andrew Lenharth16113432006-09-26 20:02:30 +0000856 // For Pic, the sequence is:
857 // BRIND(load(Jumptable + index) + RelocBase)
858 // RelocBase is the JumpTable on PPC and X86, GOT on Alpha
Andrew Lenharth82c3d8f2006-10-11 04:29:42 +0000859 SDOperand Reloc;
860 if (TLI.usesGlobalOffsetTable())
861 Reloc = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, PTy);
862 else
863 Reloc = TAB;
Chris Lattnere236ac62006-10-22 22:47:10 +0000864 ADD = (PTy != MVT::i32) ? DAG.getNode(ISD::SIGN_EXTEND, PTy, LD) : LD;
865 ADD = DAG.getNode(ISD::ADD, PTy, ADD, Reloc);
Nate Begeman2f1ae882006-07-27 01:13:04 +0000866 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), ADD));
867 } else {
868 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
869 }
Nate Begeman37efe672006-04-22 18:53:45 +0000870}
871
Nate Begemanf15485a2006-03-27 01:32:24 +0000872void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
873 // Figure out which block is immediately after the current one.
874 MachineBasicBlock *NextBlock = 0;
875 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +0000876
Nate Begemanf15485a2006-03-27 01:32:24 +0000877 if (++BBI != CurMBB->getParent()->end())
878 NextBlock = BBI;
879
Chris Lattnerd2c1d222006-10-22 21:36:53 +0000880 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
881
Nate Begemanf15485a2006-03-27 01:32:24 +0000882 // If there is only the default destination, branch to it if it is not the
883 // next basic block. Otherwise, just fall through.
884 if (I.getNumOperands() == 2) {
885 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +0000886
Nate Begemanf15485a2006-03-27 01:32:24 +0000887 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +0000888 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +0000889 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +0000890 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +0000891
Chris Lattnerd2c1d222006-10-22 21:36:53 +0000892 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000893 return;
894 }
895
896 // If there are any non-default case statements, create a vector of Cases
897 // representing each one, and sort the vector so that we can efficiently
898 // create a binary search tree from them.
899 std::vector<Case> Cases;
Bill Wendlingc70ddad2006-10-19 21:46:38 +0000900
Nate Begemanf15485a2006-03-27 01:32:24 +0000901 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
902 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
903 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
904 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +0000905
Nate Begemanf15485a2006-03-27 01:32:24 +0000906 std::sort(Cases.begin(), Cases.end(), CaseCmp());
907
908 // Get the Value to be switched on and default basic blocks, which will be
909 // inserted into CaseBlock records, representing basic blocks in the binary
910 // search tree.
911 Value *SV = I.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +0000912
913 // Get the MachineFunction which holds the current MBB. This is used during
914 // emission of jump tables, and when inserting any additional MBBs necessary
915 // to represent the switch.
Nate Begemanf15485a2006-03-27 01:32:24 +0000916 MachineFunction *CurMF = CurMBB->getParent();
917 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattnerd2c1d222006-10-22 21:36:53 +0000918
919 // If the switch has few cases (two or less) emit a series of specific
920 // tests.
Chris Lattnerb2e806e2006-10-22 23:00:53 +0000921 if (Cases.size() < 3) {
Chris Lattnerd2c1d222006-10-22 21:36:53 +0000922 // TODO: If any two of the cases has the same destination, and if one value
923 // is the same as the other, but has one bit unset that the other has set,
924 // use bit manipulation to do two compares at once. For example:
925 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
926
Chris Lattnerb3543432006-10-23 18:38:22 +0000927 // Rearrange the case blocks so that the last one falls through if possible.
928 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
929 // The last case block won't fall through into 'NextBlock' if we emit the
930 // branches in this order. See if rearranging a case value would help.
931 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
932 if (Cases[i].second == NextBlock) {
933 std::swap(Cases[i], Cases.back());
934 break;
935 }
936 }
937 }
938
Chris Lattnerd2c1d222006-10-22 21:36:53 +0000939 // Create a CaseBlock record representing a conditional branch to
940 // the Case's target mbb if the value being switched on SV is equal
941 // to C.
942 MachineBasicBlock *CurBlock = CurMBB;
943 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
944 MachineBasicBlock *FallThrough;
945 if (i != e-1) {
946 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
947 CurMF->getBasicBlockList().insert(BBI, FallThrough);
948 } else {
949 // If the last case doesn't match, go to the default block.
950 FallThrough = Default;
951 }
952
953 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
954 Cases[i].second, FallThrough, CurBlock);
955
956 // If emitting the first comparison, just call visitSwitchCase to emit the
957 // code into the current block. Otherwise, push the CaseBlock onto the
958 // vector to be later processed by SDISel, and insert the node's MBB
959 // before the next MBB.
960 if (CurBlock == CurMBB)
961 visitSwitchCase(CB);
962 else
963 SwitchCases.push_back(CB);
964
965 CurBlock = FallThrough;
966 }
967 return;
968 }
Nate Begeman37efe672006-04-22 18:53:45 +0000969
Nate Begeman17c275f2006-05-08 16:51:36 +0000970 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
971 // target supports indirect branches, then emit a jump table rather than
972 // lowering the switch to a binary tree of conditional branches.
Nate Begeman9453eea2006-04-23 06:26:20 +0000973 if (TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
Nate Begemanf4360a42006-05-03 03:48:02 +0000974 Cases.size() > 5) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000975 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
976 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
Nate Begemanf4360a42006-05-03 03:48:02 +0000977 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
978
Nate Begeman17c275f2006-05-08 16:51:36 +0000979 if (Density >= 0.3125) {
Nate Begeman37efe672006-04-22 18:53:45 +0000980 // Create a new basic block to hold the code for loading the address
981 // of the jump table, and jumping to it. Update successor information;
982 // we will either branch to the default case for the switch, or the jump
983 // table.
984 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
985 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
986 CurMBB->addSuccessor(Default);
987 CurMBB->addSuccessor(JumpTableBB);
988
989 // Subtract the lowest switch case value from the value being switched on
990 // and conditional branch to default mbb if the result is greater than the
991 // difference between smallest and largest cases.
992 SDOperand SwitchOp = getValue(SV);
993 MVT::ValueType VT = SwitchOp.getValueType();
994 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
995 DAG.getConstant(First, VT));
996
997 // The SDNode we just created, which holds the value being switched on
998 // minus the the smallest case value, needs to be copied to a virtual
999 // register so it can be used as an index into the jump table in a
1000 // subsequent basic block. This value may be smaller or larger than the
1001 // target's pointer type, and therefore require extension or truncating.
1002 if (VT > TLI.getPointerTy())
1003 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1004 else
1005 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001006
Nate Begeman37efe672006-04-22 18:53:45 +00001007 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1008 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1009
1010 // Emit the range check for the jump table, and branch to the default
1011 // block for the switch statement if the value being switched on exceeds
1012 // the largest case in the switch.
1013 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1014 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1015 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1016 DAG.getBasicBlock(Default)));
1017
Nate Begemanf4360a42006-05-03 03:48:02 +00001018 // Build a vector of destination BBs, corresponding to each target
1019 // of the jump table. If the value of the jump table slot corresponds to
1020 // a case statement, push the case's BB onto the vector, otherwise, push
1021 // the default BB.
Nate Begeman37efe672006-04-22 18:53:45 +00001022 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemanf4360a42006-05-03 03:48:02 +00001023 uint64_t TEI = First;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001024 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Reid Spencerb83eb642006-10-20 07:07:24 +00001025 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
Nate Begemanf4360a42006-05-03 03:48:02 +00001026 DestBBs.push_back(ii->second);
Nate Begemanf4360a42006-05-03 03:48:02 +00001027 ++ii;
1028 } else {
1029 DestBBs.push_back(Default);
Nate Begemanf4360a42006-05-03 03:48:02 +00001030 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001031
1032 // Update successor info
Chris Lattnerc66764c2006-09-10 06:36:57 +00001033 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1034 E = DestBBs.end(); I != E; ++I)
1035 JumpTableBB->addSuccessor(*I);
Nate Begemanf4360a42006-05-03 03:48:02 +00001036
1037 // Create a jump table index for this jump table, or return an existing
1038 // one.
Nate Begeman37efe672006-04-22 18:53:45 +00001039 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1040
1041 // Set the jump table information so that we can codegen it as a second
1042 // MachineBasicBlock
1043 JT.Reg = JumpTableReg;
1044 JT.JTI = JTI;
1045 JT.MBB = JumpTableBB;
Nate Begeman9453eea2006-04-23 06:26:20 +00001046 JT.Default = Default;
Nate Begeman37efe672006-04-22 18:53:45 +00001047 return;
1048 }
1049 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001050
1051 // Push the initial CaseRec onto the worklist
1052 std::vector<CaseRec> CaseVec;
1053 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1054
1055 while (!CaseVec.empty()) {
1056 // Grab a record representing a case range to process off the worklist
1057 CaseRec CR = CaseVec.back();
1058 CaseVec.pop_back();
1059
1060 // Size is the number of Cases represented by this range. If Size is 1,
1061 // then we are processing a leaf of the binary search tree. Otherwise,
1062 // we need to pick a pivot, and push left and right ranges onto the
1063 // worklist.
1064 unsigned Size = CR.Range.second - CR.Range.first;
1065
1066 if (Size == 1) {
1067 // Create a CaseBlock record representing a conditional branch to
1068 // the Case's target mbb if the value being switched on SV is equal
1069 // to C. Otherwise, branch to default.
1070 Constant *C = CR.Range.first->first;
1071 MachineBasicBlock *Target = CR.Range.first->second;
1072 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1073 CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001074
Nate Begemanf15485a2006-03-27 01:32:24 +00001075 // If the MBB representing the leaf node is the current MBB, then just
1076 // call visitSwitchCase to emit the code into the current block.
1077 // Otherwise, push the CaseBlock onto the vector to be later processed
1078 // by SDISel, and insert the node's MBB before the next MBB.
1079 if (CR.CaseBB == CurMBB)
1080 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001081 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001082 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001083 } else {
1084 // split case range at pivot
1085 CaseItr Pivot = CR.Range.first + (Size / 2);
1086 CaseRange LHSR(CR.Range.first, Pivot);
1087 CaseRange RHSR(Pivot, CR.Range.second);
1088 Constant *C = Pivot->first;
Chris Lattner57ab6592006-10-24 17:57:59 +00001089 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001090
Nate Begemanf15485a2006-03-27 01:32:24 +00001091 // We know that we branch to the LHS if the Value being switched on is
1092 // less than the Pivot value, C. We use this to optimize our binary
1093 // tree a bit, by recognizing that if SV is greater than or equal to the
1094 // LHS's Case Value, and that Case Value is exactly one less than the
1095 // Pivot's Value, then we can branch directly to the LHS's Target,
1096 // rather than creating a leaf node for it.
1097 if ((LHSR.second - LHSR.first) == 1 &&
1098 LHSR.first->first == CR.GE &&
Reid Spencerb83eb642006-10-20 07:07:24 +00001099 cast<ConstantIntegral>(C)->getZExtValue() ==
1100 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001101 TrueBB = LHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001102 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001103 TrueBB = new MachineBasicBlock(LLVMBB);
1104 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1105 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001106 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001107
Nate Begemanf15485a2006-03-27 01:32:24 +00001108 // Similar to the optimization above, if the Value being switched on is
1109 // known to be less than the Constant CR.LT, and the current Case Value
1110 // is CR.LT - 1, then we can branch directly to the target block for
1111 // the current Case Value, rather than emitting a RHS leaf node for it.
1112 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Reid Spencerb83eb642006-10-20 07:07:24 +00001113 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1114 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001115 FalseBB = RHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001116 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001117 FalseBB = new MachineBasicBlock(LLVMBB);
1118 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1119 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001120 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001121
Nate Begemanf15485a2006-03-27 01:32:24 +00001122 // Create a CaseBlock record representing a conditional branch to
1123 // the LHS node if the value being switched on SV is less than C.
1124 // Otherwise, branch to LHS.
1125 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
Chris Lattner57ab6592006-10-24 17:57:59 +00001126 SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001127
Nate Begemanf15485a2006-03-27 01:32:24 +00001128 if (CR.CaseBB == CurMBB)
1129 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001130 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001131 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001132 }
1133 }
1134}
1135
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001136void SelectionDAGLowering::visitSub(User &I) {
1137 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +00001138 if (I.getType()->isFloatingPoint()) {
1139 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1140 if (CFP->isExactlyValue(-0.0)) {
1141 SDOperand Op2 = getValue(I.getOperand(1));
1142 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1143 return;
1144 }
Chris Lattner01b3d732005-09-28 22:28:18 +00001145 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001146 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001147}
1148
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001149void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
1150 unsigned VecOp) {
1151 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001152 SDOperand Op1 = getValue(I.getOperand(0));
1153 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +00001154
Chris Lattnerb67eb912005-11-19 18:40:42 +00001155 if (Ty->isIntegral()) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001156 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1157 } else if (Ty->isFloatingPoint()) {
1158 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1159 } else {
1160 const PackedType *PTy = cast<PackedType>(Ty);
Chris Lattnerc7029802006-03-18 01:44:44 +00001161 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1162 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1163 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001164 }
Nate Begemane21ea612005-11-18 07:42:56 +00001165}
Chris Lattner2c49f272005-01-19 22:31:21 +00001166
Nate Begemane21ea612005-11-18 07:42:56 +00001167void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1168 SDOperand Op1 = getValue(I.getOperand(0));
1169 SDOperand Op2 = getValue(I.getOperand(1));
1170
1171 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1172
Chris Lattner1c08c712005-01-07 07:47:53 +00001173 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1174}
1175
1176void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
Evan Chengf6f95812006-05-23 06:40:47 +00001177 ISD::CondCode UnsignedOpcode,
1178 ISD::CondCode FPOpcode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001179 SDOperand Op1 = getValue(I.getOperand(0));
1180 SDOperand Op2 = getValue(I.getOperand(1));
1181 ISD::CondCode Opcode = SignedOpcode;
Evan Cheng80235d52006-05-23 18:18:46 +00001182 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
Evan Chengf6f95812006-05-23 06:40:47 +00001183 Opcode = FPOpcode;
1184 else if (I.getOperand(0)->getType()->isUnsigned())
Chris Lattner1c08c712005-01-07 07:47:53 +00001185 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +00001186 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +00001187}
1188
1189void SelectionDAGLowering::visitSelect(User &I) {
1190 SDOperand Cond = getValue(I.getOperand(0));
1191 SDOperand TrueVal = getValue(I.getOperand(1));
1192 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattnerb22e35a2006-04-08 22:22:57 +00001193 if (!isa<PackedType>(I.getType())) {
1194 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1195 TrueVal, FalseVal));
1196 } else {
1197 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1198 *(TrueVal.Val->op_end()-2),
1199 *(TrueVal.Val->op_end()-1)));
1200 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001201}
1202
1203void SelectionDAGLowering::visitCast(User &I) {
1204 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00001205 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001206 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner1c08c712005-01-07 07:47:53 +00001207
Chris Lattnere25ca692006-03-22 20:09:35 +00001208 if (DestVT == MVT::Vector) {
1209 // This is a cast to a vector from something else. This is always a bit
1210 // convert. Get information about the input vector.
1211 const PackedType *DestTy = cast<PackedType>(I.getType());
1212 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1213 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1214 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1215 DAG.getValueType(EltVT)));
1216 } else if (SrcVT == DestVT) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001217 setValue(&I, N); // noop cast.
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001218 } else if (DestVT == MVT::i1) {
Chris Lattneref311aa2005-05-09 22:17:13 +00001219 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001220 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattneref311aa2005-05-09 22:17:13 +00001221 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +00001222 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001223 } else if (isInteger(SrcVT)) {
1224 if (isInteger(DestVT)) { // Int -> Int cast
1225 if (DestVT < SrcVT) // Truncating cast?
1226 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001227 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001228 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001229 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001230 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattner7e358902006-03-22 22:20:49 +00001231 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001232 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001233 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001234 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001235 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattnere25ca692006-03-22 20:09:35 +00001236 } else {
1237 assert(0 && "Unknown cast!");
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001238 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001239 } else if (isFloatingPoint(SrcVT)) {
1240 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1241 if (DestVT < SrcVT) // Rounding cast?
1242 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001243 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001244 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattnere25ca692006-03-22 20:09:35 +00001245 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001246 if (I.getType()->isSigned())
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001247 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattnerae0aacb2005-01-08 08:08:56 +00001248 else
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001249 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattnere25ca692006-03-22 20:09:35 +00001250 } else {
1251 assert(0 && "Unknown cast!");
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001252 }
1253 } else {
Chris Lattnere25ca692006-03-22 20:09:35 +00001254 assert(SrcVT == MVT::Vector && "Unknown cast!");
1255 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1256 // This is a cast from a vector to something else. This is always a bit
1257 // convert. Get information about the input vector.
1258 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner1c08c712005-01-07 07:47:53 +00001259 }
1260}
1261
Chris Lattner2bbd8102006-03-29 00:11:43 +00001262void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001263 SDOperand InVec = getValue(I.getOperand(0));
1264 SDOperand InVal = getValue(I.getOperand(1));
1265 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1266 getValue(I.getOperand(2)));
1267
Chris Lattner2332b9f2006-03-19 01:17:20 +00001268 SDOperand Num = *(InVec.Val->op_end()-2);
1269 SDOperand Typ = *(InVec.Val->op_end()-1);
1270 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1271 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00001272}
1273
Chris Lattner2bbd8102006-03-29 00:11:43 +00001274void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00001275 SDOperand InVec = getValue(I.getOperand(0));
1276 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1277 getValue(I.getOperand(1)));
1278 SDOperand Typ = *(InVec.Val->op_end()-1);
1279 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1280 TLI.getValueType(I.getType()), InVec, InIdx));
1281}
Chris Lattnerc7029802006-03-18 01:44:44 +00001282
Chris Lattner3e104b12006-04-08 04:15:24 +00001283void SelectionDAGLowering::visitShuffleVector(User &I) {
1284 SDOperand V1 = getValue(I.getOperand(0));
1285 SDOperand V2 = getValue(I.getOperand(1));
1286 SDOperand Mask = getValue(I.getOperand(2));
1287
1288 SDOperand Num = *(V1.Val->op_end()-2);
1289 SDOperand Typ = *(V2.Val->op_end()-1);
1290 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1291 V1, V2, Mask, Num, Typ));
1292}
1293
1294
Chris Lattner1c08c712005-01-07 07:47:53 +00001295void SelectionDAGLowering::visitGetElementPtr(User &I) {
1296 SDOperand N = getValue(I.getOperand(0));
1297 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001298
1299 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1300 OI != E; ++OI) {
1301 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001302 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001303 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00001304 if (Field) {
1305 // N = N + Offset
Owen Andersona69571c2006-05-03 01:29:57 +00001306 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner1c08c712005-01-07 07:47:53 +00001307 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001308 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00001309 }
1310 Ty = StTy->getElementType(Field);
1311 } else {
1312 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00001313
Chris Lattner7c0104b2005-11-09 04:45:33 +00001314 // If this is a constant subscript, handle it quickly.
1315 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001316 if (CI->getZExtValue() == 0) continue;
Chris Lattner7c0104b2005-11-09 04:45:33 +00001317 uint64_t Offs;
Reid Spencerb83eb642006-10-20 07:07:24 +00001318 if (CI->getType()->isSigned())
1319 Offs = (int64_t)
1320 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001321 else
Reid Spencerb83eb642006-10-20 07:07:24 +00001322 Offs =
1323 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001324 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1325 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00001326 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00001327
1328 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00001329 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001330 SDOperand IdxN = getValue(Idx);
1331
1332 // If the index is smaller or larger than intptr_t, truncate or extend
1333 // it.
1334 if (IdxN.getValueType() < N.getValueType()) {
1335 if (Idx->getType()->isSigned())
1336 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1337 else
1338 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1339 } else if (IdxN.getValueType() > N.getValueType())
1340 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1341
1342 // If this is a multiply by a power of two, turn it into a shl
1343 // immediately. This is a very common case.
1344 if (isPowerOf2_64(ElementSize)) {
1345 unsigned Amt = Log2_64(ElementSize);
1346 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00001347 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00001348 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1349 continue;
1350 }
1351
1352 SDOperand Scale = getIntPtrConstant(ElementSize);
1353 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1354 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00001355 }
1356 }
1357 setValue(&I, N);
1358}
1359
1360void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1361 // If this is a fixed sized alloca in the entry block of the function,
1362 // allocate it statically on the stack.
1363 if (FuncInfo.StaticAllocaMap.count(&I))
1364 return; // getValue will auto-populate this.
1365
1366 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00001367 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1368 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +00001369 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00001370
1371 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00001372 MVT::ValueType IntPtr = TLI.getPointerTy();
1373 if (IntPtr < AllocSize.getValueType())
1374 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1375 else if (IntPtr > AllocSize.getValueType())
1376 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00001377
Chris Lattner68cd65e2005-01-22 23:04:37 +00001378 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00001379 getIntPtrConstant(TySize));
1380
1381 // Handle alignment. If the requested alignment is less than or equal to the
1382 // stack alignment, ignore it and round the size of the allocation up to the
1383 // stack alignment size. If the size is greater than the stack alignment, we
1384 // note this in the DYNAMIC_STACKALLOC node.
1385 unsigned StackAlign =
1386 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1387 if (Align <= StackAlign) {
1388 Align = 0;
1389 // Add SA-1 to the size.
1390 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1391 getIntPtrConstant(StackAlign-1));
1392 // Mask out the low bits for alignment purposes.
1393 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1394 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1395 }
1396
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001397 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001398 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1399 MVT::Other);
1400 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner1c08c712005-01-07 07:47:53 +00001401 DAG.setRoot(setValue(&I, DSA).getValue(1));
1402
1403 // Inform the Frame Information that we have just allocated a variable-sized
1404 // object.
1405 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1406}
1407
Chris Lattner1c08c712005-01-07 07:47:53 +00001408void SelectionDAGLowering::visitLoad(LoadInst &I) {
1409 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00001410
Chris Lattnerd3948112005-01-17 22:19:26 +00001411 SDOperand Root;
1412 if (I.isVolatile())
1413 Root = getRoot();
1414 else {
1415 // Do not serialize non-volatile loads against each other.
1416 Root = DAG.getRoot();
1417 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001418
Evan Cheng466685d2006-10-09 20:57:25 +00001419 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001420 Root, I.isVolatile()));
1421}
1422
1423SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00001424 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001425 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001426 SDOperand L;
Nate Begeman8cfa57b2005-12-06 06:18:55 +00001427 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00001428 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00001429 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1430 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001431 } else {
Evan Cheng466685d2006-10-09 20:57:25 +00001432 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001433 }
Chris Lattnerd3948112005-01-17 22:19:26 +00001434
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001435 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00001436 DAG.setRoot(L.getValue(1));
1437 else
1438 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001439
1440 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00001441}
1442
1443
1444void SelectionDAGLowering::visitStore(StoreInst &I) {
1445 Value *SrcV = I.getOperand(0);
1446 SDOperand Src = getValue(SrcV);
1447 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng8b2794a2006-10-13 21:14:26 +00001448 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1449 I.isVolatile()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001450}
1451
Chris Lattner0eade312006-03-24 02:22:33 +00001452/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1453/// access memory and has no other side effects at all.
1454static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1455#define GET_NO_MEMORY_INTRINSICS
1456#include "llvm/Intrinsics.gen"
1457#undef GET_NO_MEMORY_INTRINSICS
1458 return false;
1459}
1460
Chris Lattnere58a7802006-04-02 03:41:14 +00001461// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1462// have any side-effects or if it only reads memory.
1463static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1464#define GET_SIDE_EFFECT_INFO
1465#include "llvm/Intrinsics.gen"
1466#undef GET_SIDE_EFFECT_INFO
1467 return false;
1468}
1469
Chris Lattner0eade312006-03-24 02:22:33 +00001470/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1471/// node.
1472void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1473 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00001474 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00001475 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00001476
1477 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001478 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00001479 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1480 if (OnlyLoad) {
1481 // We don't need to serialize loads against other loads.
1482 Ops.push_back(DAG.getRoot());
1483 } else {
1484 Ops.push_back(getRoot());
1485 }
1486 }
Chris Lattner0eade312006-03-24 02:22:33 +00001487
1488 // Add the intrinsic ID as an integer operand.
1489 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1490
1491 // Add all operands of the call to the operand list.
1492 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1493 SDOperand Op = getValue(I.getOperand(i));
1494
1495 // If this is a vector type, force it to the right packed type.
1496 if (Op.getValueType() == MVT::Vector) {
1497 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1498 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1499
1500 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1501 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1502 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1503 }
1504
1505 assert(TLI.isTypeLegal(Op.getValueType()) &&
1506 "Intrinsic uses a non-legal type?");
1507 Ops.push_back(Op);
1508 }
1509
1510 std::vector<MVT::ValueType> VTs;
1511 if (I.getType() != Type::VoidTy) {
1512 MVT::ValueType VT = TLI.getValueType(I.getType());
1513 if (VT == MVT::Vector) {
1514 const PackedType *DestTy = cast<PackedType>(I.getType());
1515 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1516
1517 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1518 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1519 }
1520
1521 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1522 VTs.push_back(VT);
1523 }
1524 if (HasChain)
1525 VTs.push_back(MVT::Other);
1526
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001527 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1528
Chris Lattner0eade312006-03-24 02:22:33 +00001529 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00001530 SDOperand Result;
1531 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001532 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1533 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001534 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001535 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1536 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001537 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001538 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1539 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001540
Chris Lattnere58a7802006-04-02 03:41:14 +00001541 if (HasChain) {
1542 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1543 if (OnlyLoad)
1544 PendingLoads.push_back(Chain);
1545 else
1546 DAG.setRoot(Chain);
1547 }
Chris Lattner0eade312006-03-24 02:22:33 +00001548 if (I.getType() != Type::VoidTy) {
1549 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1550 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1551 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1552 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1553 DAG.getValueType(EVT));
1554 }
1555 setValue(&I, Result);
1556 }
1557}
1558
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001559/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1560/// we want to emit this as a call to a named external function, return the name
1561/// otherwise lower it and return null.
1562const char *
1563SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1564 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00001565 default:
1566 // By default, turn this into a target intrinsic node.
1567 visitTargetIntrinsic(I, Intrinsic);
1568 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001569 case Intrinsic::vastart: visitVAStart(I); return 0;
1570 case Intrinsic::vaend: visitVAEnd(I); return 0;
1571 case Intrinsic::vacopy: visitVACopy(I); return 0;
1572 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1573 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1574 case Intrinsic::setjmp:
1575 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1576 break;
1577 case Intrinsic::longjmp:
1578 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1579 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00001580 case Intrinsic::memcpy_i32:
1581 case Intrinsic::memcpy_i64:
1582 visitMemIntrinsic(I, ISD::MEMCPY);
1583 return 0;
1584 case Intrinsic::memset_i32:
1585 case Intrinsic::memset_i64:
1586 visitMemIntrinsic(I, ISD::MEMSET);
1587 return 0;
1588 case Intrinsic::memmove_i32:
1589 case Intrinsic::memmove_i64:
1590 visitMemIntrinsic(I, ISD::MEMMOVE);
1591 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001592
Chris Lattner86cb6432005-12-13 17:40:33 +00001593 case Intrinsic::dbg_stoppoint: {
Jim Laskeyce72b172006-02-11 01:01:30 +00001594 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00001595 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001596 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001597 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00001598
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001599 Ops[0] = getRoot();
1600 Ops[1] = getValue(SPI.getLineValue());
1601 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00001602
Jim Laskey43970fe2006-03-23 18:06:46 +00001603 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00001604 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00001605 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1606
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001607 Ops[3] = DAG.getString(CompileUnit->getFileName());
1608 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00001609
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001610 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00001611 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001612
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001613 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00001614 }
Jim Laskey43970fe2006-03-23 18:06:46 +00001615 case Intrinsic::dbg_region_start: {
1616 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1617 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001618 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001619 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001620 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1621 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00001622 }
1623
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001624 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001625 }
1626 case Intrinsic::dbg_region_end: {
1627 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1628 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001629 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001630 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001631 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1632 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00001633 }
1634
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001635 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001636 }
1637 case Intrinsic::dbg_func_start: {
1638 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1639 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskeyfbcf23c2006-03-26 22:46:27 +00001640 if (DebugInfo && FSI.getSubprogram() &&
1641 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskey43970fe2006-03-23 18:06:46 +00001642 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001643 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1644 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00001645 }
1646
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001647 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00001648 }
1649 case Intrinsic::dbg_declare: {
1650 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1651 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskeybf7637d2006-03-28 13:45:20 +00001652 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00001653 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001654 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey43970fe2006-03-23 18:06:46 +00001655 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00001656 }
1657
1658 return 0;
1659 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001660
Reid Spencer0b118202006-01-16 21:12:35 +00001661 case Intrinsic::isunordered_f32:
1662 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001663 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1664 getValue(I.getOperand(2)), ISD::SETUO));
1665 return 0;
1666
Reid Spencer0b118202006-01-16 21:12:35 +00001667 case Intrinsic::sqrt_f32:
1668 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001669 setValue(&I, DAG.getNode(ISD::FSQRT,
1670 getValue(I.getOperand(1)).getValueType(),
1671 getValue(I.getOperand(1))));
1672 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00001673 case Intrinsic::powi_f32:
1674 case Intrinsic::powi_f64:
1675 setValue(&I, DAG.getNode(ISD::FPOWI,
1676 getValue(I.getOperand(1)).getValueType(),
1677 getValue(I.getOperand(1)),
1678 getValue(I.getOperand(2))));
1679 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001680 case Intrinsic::pcmarker: {
1681 SDOperand Tmp = getValue(I.getOperand(1));
1682 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1683 return 0;
1684 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001685 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001686 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001687 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
1688 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
1689 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001690 setValue(&I, Tmp);
1691 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00001692 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001693 }
Nate Begemand88fc032006-01-14 03:14:10 +00001694 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00001695 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00001696 case Intrinsic::bswap_i64:
1697 setValue(&I, DAG.getNode(ISD::BSWAP,
1698 getValue(I.getOperand(1)).getValueType(),
1699 getValue(I.getOperand(1))));
1700 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001701 case Intrinsic::cttz_i8:
1702 case Intrinsic::cttz_i16:
1703 case Intrinsic::cttz_i32:
1704 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001705 setValue(&I, DAG.getNode(ISD::CTTZ,
1706 getValue(I.getOperand(1)).getValueType(),
1707 getValue(I.getOperand(1))));
1708 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001709 case Intrinsic::ctlz_i8:
1710 case Intrinsic::ctlz_i16:
1711 case Intrinsic::ctlz_i32:
1712 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001713 setValue(&I, DAG.getNode(ISD::CTLZ,
1714 getValue(I.getOperand(1)).getValueType(),
1715 getValue(I.getOperand(1))));
1716 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001717 case Intrinsic::ctpop_i8:
1718 case Intrinsic::ctpop_i16:
1719 case Intrinsic::ctpop_i32:
1720 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001721 setValue(&I, DAG.getNode(ISD::CTPOP,
1722 getValue(I.getOperand(1)).getValueType(),
1723 getValue(I.getOperand(1))));
1724 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00001725 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001726 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001727 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
1728 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00001729 setValue(&I, Tmp);
1730 DAG.setRoot(Tmp.getValue(1));
1731 return 0;
1732 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00001733 case Intrinsic::stackrestore: {
1734 SDOperand Tmp = getValue(I.getOperand(1));
1735 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00001736 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00001737 }
Chris Lattnerac22c832005-12-12 22:51:16 +00001738 case Intrinsic::prefetch:
1739 // FIXME: Currently discarding prefetches.
1740 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001741 }
1742}
1743
1744
Chris Lattner1c08c712005-01-07 07:47:53 +00001745void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00001746 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001747 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001748 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001749 if (unsigned IID = F->getIntrinsicID()) {
1750 RenameFn = visitIntrinsicCall(I, IID);
1751 if (!RenameFn)
1752 return;
1753 } else { // Not an LLVM intrinsic.
1754 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00001755 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1756 if (I.getNumOperands() == 3 && // Basic sanity checks.
1757 I.getOperand(1)->getType()->isFloatingPoint() &&
1758 I.getType() == I.getOperand(1)->getType() &&
1759 I.getType() == I.getOperand(2)->getType()) {
1760 SDOperand LHS = getValue(I.getOperand(1));
1761 SDOperand RHS = getValue(I.getOperand(2));
1762 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1763 LHS, RHS));
1764 return;
1765 }
1766 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001767 if (I.getNumOperands() == 2 && // Basic sanity checks.
1768 I.getOperand(1)->getType()->isFloatingPoint() &&
1769 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001770 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00001771 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1772 return;
1773 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001774 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001775 if (I.getNumOperands() == 2 && // Basic sanity checks.
1776 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001777 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001778 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001779 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1780 return;
1781 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001782 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001783 if (I.getNumOperands() == 2 && // Basic sanity checks.
1784 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001785 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001786 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001787 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1788 return;
1789 }
1790 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00001791 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00001792 } else if (isa<InlineAsm>(I.getOperand(0))) {
1793 visitInlineAsm(I);
1794 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001795 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001796
Chris Lattner64e14b12005-01-08 22:48:57 +00001797 SDOperand Callee;
1798 if (!RenameFn)
1799 Callee = getValue(I.getOperand(0));
1800 else
1801 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00001802 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001803 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00001804 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1805 Value *Arg = I.getOperand(i);
1806 SDOperand ArgNode = getValue(Arg);
1807 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1808 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001809
Nate Begeman8e21e712005-03-26 01:29:23 +00001810 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1811 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00001812
Chris Lattnercf5734d2005-01-08 19:26:18 +00001813 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00001814 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00001815 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00001816 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00001817 setValue(&I, Result.first);
1818 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001819}
1820
Chris Lattner864635a2006-02-22 22:37:12 +00001821SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001822 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00001823 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1824 Chain = Val.getValue(1);
1825 Flag = Val.getValue(2);
1826
1827 // If the result was expanded, copy from the top part.
1828 if (Regs.size() > 1) {
1829 assert(Regs.size() == 2 &&
1830 "Cannot expand to more than 2 elts yet!");
1831 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00001832 Chain = Hi.getValue(1);
1833 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00001834 if (DAG.getTargetLoweringInfo().isLittleEndian())
1835 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1836 else
1837 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00001838 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00001839
Chris Lattnercf752aa2006-06-08 18:22:48 +00001840 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00001841 // appropriate type.
1842 if (RegVT == ValueVT)
1843 return Val;
1844
Chris Lattnercf752aa2006-06-08 18:22:48 +00001845 if (MVT::isInteger(RegVT)) {
1846 if (ValueVT < RegVT)
1847 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1848 else
1849 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
1850 } else {
Chris Lattner864635a2006-02-22 22:37:12 +00001851 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00001852 }
Chris Lattner864635a2006-02-22 22:37:12 +00001853}
1854
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001855/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1856/// specified value into the registers specified by this object. This uses
1857/// Chain/Flag as the input and updates them for the output Chain/Flag.
1858void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00001859 SDOperand &Chain, SDOperand &Flag,
1860 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001861 if (Regs.size() == 1) {
1862 // If there is a single register and the types differ, this must be
1863 // a promotion.
1864 if (RegVT != ValueVT) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00001865 if (MVT::isInteger(RegVT)) {
1866 if (RegVT < ValueVT)
1867 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
1868 else
1869 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1870 } else
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001871 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1872 }
1873 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1874 Flag = Chain.getValue(1);
1875 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00001876 std::vector<unsigned> R(Regs);
1877 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1878 std::reverse(R.begin(), R.end());
1879
1880 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001881 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00001882 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00001883 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001884 Flag = Chain.getValue(1);
1885 }
1886 }
1887}
Chris Lattner864635a2006-02-22 22:37:12 +00001888
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001889/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1890/// operand list. This adds the code marker and includes the number of
1891/// values added into it.
1892void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001893 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001894 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1895 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1896 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1897}
Chris Lattner864635a2006-02-22 22:37:12 +00001898
1899/// isAllocatableRegister - If the specified register is safe to allocate,
1900/// i.e. it isn't a stack pointer or some other special register, return the
1901/// register class for the register. Otherwise, return null.
1902static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001903isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1904 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001905 MVT::ValueType FoundVT = MVT::Other;
1906 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001907 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1908 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001909 MVT::ValueType ThisVT = MVT::Other;
1910
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001911 const TargetRegisterClass *RC = *RCI;
1912 // If none of the the value types for this register class are valid, we
1913 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001914 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1915 I != E; ++I) {
1916 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001917 // If we have already found this register in a different register class,
1918 // choose the one with the largest VT specified. For example, on
1919 // PowerPC, we favor f64 register classes over f32.
1920 if (FoundVT == MVT::Other ||
1921 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
1922 ThisVT = *I;
1923 break;
1924 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001925 }
1926 }
1927
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001928 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001929
Chris Lattner864635a2006-02-22 22:37:12 +00001930 // NOTE: This isn't ideal. In particular, this might allocate the
1931 // frame pointer in functions that need it (due to them not being taken
1932 // out of allocation, because a variable sized allocation hasn't been seen
1933 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001934 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1935 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001936 if (*I == Reg) {
1937 // We found a matching register class. Keep looking at others in case
1938 // we find one with larger registers that this physreg is also in.
1939 FoundRC = RC;
1940 FoundVT = ThisVT;
1941 break;
1942 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00001943 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00001944 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00001945}
1946
1947RegsForValue SelectionDAGLowering::
1948GetRegistersForValue(const std::string &ConstrCode,
1949 MVT::ValueType VT, bool isOutReg, bool isInReg,
1950 std::set<unsigned> &OutputRegs,
1951 std::set<unsigned> &InputRegs) {
1952 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1953 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1954 std::vector<unsigned> Regs;
1955
1956 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1957 MVT::ValueType RegVT;
1958 MVT::ValueType ValueVT = VT;
1959
1960 if (PhysReg.first) {
1961 if (VT == MVT::Other)
1962 ValueVT = *PhysReg.second->vt_begin();
Chris Lattnercf752aa2006-06-08 18:22:48 +00001963
1964 // Get the actual register value type. This is important, because the user
1965 // may have asked for (e.g.) the AX register in i32 type. We need to
1966 // remember that AX is actually i16 to get the right extension.
1967 RegVT = *PhysReg.second->vt_begin();
Chris Lattner864635a2006-02-22 22:37:12 +00001968
1969 // This is a explicit reference to a physical register.
1970 Regs.push_back(PhysReg.first);
1971
1972 // If this is an expanded reference, add the rest of the regs to Regs.
1973 if (NumRegs != 1) {
Chris Lattner864635a2006-02-22 22:37:12 +00001974 TargetRegisterClass::iterator I = PhysReg.second->begin();
1975 TargetRegisterClass::iterator E = PhysReg.second->end();
1976 for (; *I != PhysReg.first; ++I)
1977 assert(I != E && "Didn't find reg!");
1978
1979 // Already added the first reg.
1980 --NumRegs; ++I;
1981 for (; NumRegs; --NumRegs, ++I) {
1982 assert(I != E && "Ran out of registers to allocate!");
1983 Regs.push_back(*I);
1984 }
1985 }
1986 return RegsForValue(Regs, RegVT, ValueVT);
1987 }
1988
1989 // This is a reference to a register class. Allocate NumRegs consecutive,
1990 // available, registers from the class.
1991 std::vector<unsigned> RegClassRegs =
1992 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1993
1994 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1995 MachineFunction &MF = *CurMBB->getParent();
1996 unsigned NumAllocated = 0;
1997 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1998 unsigned Reg = RegClassRegs[i];
1999 // See if this register is available.
2000 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2001 (isInReg && InputRegs.count(Reg))) { // Already used.
2002 // Make sure we find consecutive registers.
2003 NumAllocated = 0;
2004 continue;
2005 }
2006
2007 // Check to see if this register is allocatable (i.e. don't give out the
2008 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002009 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00002010 if (!RC) {
2011 // Make sure we find consecutive registers.
2012 NumAllocated = 0;
2013 continue;
2014 }
2015
2016 // Okay, this register is good, we can use it.
2017 ++NumAllocated;
2018
2019 // If we allocated enough consecutive
2020 if (NumAllocated == NumRegs) {
2021 unsigned RegStart = (i-NumAllocated)+1;
2022 unsigned RegEnd = i+1;
2023 // Mark all of the allocated registers used.
2024 for (unsigned i = RegStart; i != RegEnd; ++i) {
2025 unsigned Reg = RegClassRegs[i];
2026 Regs.push_back(Reg);
2027 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2028 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2029 }
2030
2031 return RegsForValue(Regs, *RC->vt_begin(), VT);
2032 }
2033 }
2034
2035 // Otherwise, we couldn't allocate enough registers for this.
2036 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00002037}
2038
Chris Lattner864635a2006-02-22 22:37:12 +00002039
Chris Lattnerce7518c2006-01-26 22:24:51 +00002040/// visitInlineAsm - Handle a call to an InlineAsm object.
2041///
2042void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2043 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2044
2045 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2046 MVT::Other);
2047
2048 // Note, we treat inline asms both with and without side-effects as the same.
2049 // If an inline asm doesn't have side effects and doesn't access memory, we
2050 // could not choose to not chain it.
2051 bool hasSideEffects = IA->hasSideEffects();
2052
Chris Lattner2cc2f662006-02-01 01:28:23 +00002053 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002054 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00002055
2056 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2057 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2058 /// if it is a def of that register.
2059 std::vector<SDOperand> AsmNodeOperands;
2060 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2061 AsmNodeOperands.push_back(AsmStr);
2062
2063 SDOperand Chain = getRoot();
2064 SDOperand Flag;
2065
Chris Lattner4e4b5762006-02-01 18:59:47 +00002066 // We fully assign registers here at isel time. This is not optimal, but
2067 // should work. For register classes that correspond to LLVM classes, we
2068 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2069 // over the constraints, collecting fixed registers that we know we can't use.
2070 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002071 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002072 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2073 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2074 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner2223aea2006-02-02 00:25:23 +00002075
Chris Lattner1efa40f2006-02-22 00:56:39 +00002076 MVT::ValueType OpVT;
2077
2078 // Compute the value type for each operand and add it to ConstraintVTs.
2079 switch (Constraints[i].Type) {
2080 case InlineAsm::isOutput:
2081 if (!Constraints[i].isIndirectOutput) {
2082 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2083 OpVT = TLI.getValueType(I.getType());
2084 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002085 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002086 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2087 OpNum++; // Consumes a call operand.
2088 }
2089 break;
2090 case InlineAsm::isInput:
2091 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2092 OpNum++; // Consumes a call operand.
2093 break;
2094 case InlineAsm::isClobber:
2095 OpVT = MVT::Other;
2096 break;
2097 }
2098
2099 ConstraintVTs.push_back(OpVT);
2100
Chris Lattner864635a2006-02-22 22:37:12 +00002101 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2102 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00002103
Chris Lattner864635a2006-02-22 22:37:12 +00002104 // Build a list of regs that this operand uses. This always has a single
2105 // element for promoted/expanded operands.
2106 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2107 false, false,
2108 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00002109
2110 switch (Constraints[i].Type) {
2111 case InlineAsm::isOutput:
2112 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002113 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002114 // If this is an early-clobber output, it cannot be assigned to the same
2115 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00002116 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00002117 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002118 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002119 case InlineAsm::isInput:
2120 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002121 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00002122 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002123 case InlineAsm::isClobber:
2124 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00002125 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2126 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002127 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002128 }
2129 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00002130
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002131 // Loop over all of the inputs, copying the operand values into the
2132 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00002133 RegsForValue RetValRegs;
2134 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002135 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002136
Chris Lattner6656dd12006-01-31 02:03:41 +00002137 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00002138 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2139 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner1efa40f2006-02-22 00:56:39 +00002140
Chris Lattner2cc2f662006-02-01 01:28:23 +00002141 switch (Constraints[i].Type) {
2142 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00002143 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2144 if (ConstraintCode.size() == 1) // not a physreg name.
2145 CTy = TLI.getConstraintType(ConstraintCode[0]);
2146
2147 if (CTy == TargetLowering::C_Memory) {
2148 // Memory output.
2149 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2150
2151 // Check that the operand (the address to store to) isn't a float.
2152 if (!MVT::isInteger(InOperandVal.getValueType()))
2153 assert(0 && "MATCH FAIL!");
2154
2155 if (!Constraints[i].isIndirectOutput)
2156 assert(0 && "MATCH FAIL!");
2157
2158 OpNum++; // Consumes a call operand.
2159
2160 // Extend/truncate to the right pointer type if needed.
2161 MVT::ValueType PtrType = TLI.getPointerTy();
2162 if (InOperandVal.getValueType() < PtrType)
2163 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2164 else if (InOperandVal.getValueType() > PtrType)
2165 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2166
2167 // Add information to the INLINEASM node to know about this output.
2168 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2169 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2170 AsmNodeOperands.push_back(InOperandVal);
2171 break;
2172 }
2173
2174 // Otherwise, this is a register output.
2175 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2176
Chris Lattner864635a2006-02-22 22:37:12 +00002177 // If this is an early-clobber output, or if there is an input
2178 // constraint that matches this, we need to reserve the input register
2179 // so no other inputs allocate to it.
2180 bool UsesInputRegister = false;
2181 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2182 UsesInputRegister = true;
2183
2184 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00002185 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00002186 RegsForValue Regs =
2187 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2188 true, UsesInputRegister,
2189 OutputRegs, InputRegs);
2190 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner1efa40f2006-02-22 00:56:39 +00002191
Chris Lattner2cc2f662006-02-01 01:28:23 +00002192 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00002193 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00002194 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00002195 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00002196 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00002197 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002198 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2199 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00002200 OpNum++; // Consumes a call operand.
2201 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002202
2203 // Add information to the INLINEASM node to know that this register is
2204 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002205 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002206 break;
2207 }
2208 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00002209 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00002210 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00002211
Chris Lattner2223aea2006-02-02 00:25:23 +00002212 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2213 // If this is required to match an output register we have already set,
2214 // just use its register.
2215 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00002216
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002217 // Scan until we find the definition we already emitted of this operand.
2218 // When we find it, create a RegsForValue operand.
2219 unsigned CurOp = 2; // The first operand.
2220 for (; OperandNo; --OperandNo) {
2221 // Advance to the next operand.
2222 unsigned NumOps =
2223 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00002224 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2225 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002226 "Skipped past definitions?");
2227 CurOp += (NumOps>>3)+1;
2228 }
2229
2230 unsigned NumOps =
2231 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2232 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2233 "Skipped past definitions?");
2234
2235 // Add NumOps>>3 registers to MatchedRegs.
2236 RegsForValue MatchedRegs;
2237 MatchedRegs.ValueVT = InOperandVal.getValueType();
2238 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2239 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2240 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2241 MatchedRegs.Regs.push_back(Reg);
2242 }
2243
2244 // Use the produced MatchedRegs object to
Evan Chenga8441262006-06-15 08:11:54 +00002245 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2246 TLI.getPointerTy());
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002247 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002248 break;
Chris Lattner2223aea2006-02-02 00:25:23 +00002249 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002250
2251 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2252 if (ConstraintCode.size() == 1) // not a physreg name.
2253 CTy = TLI.getConstraintType(ConstraintCode[0]);
2254
2255 if (CTy == TargetLowering::C_Other) {
2256 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2257 assert(0 && "MATCH FAIL!");
2258
2259 // Add information to the INLINEASM node to know about this input.
2260 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2261 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2262 AsmNodeOperands.push_back(InOperandVal);
2263 break;
2264 } else if (CTy == TargetLowering::C_Memory) {
2265 // Memory input.
2266
2267 // Check that the operand isn't a float.
2268 if (!MVT::isInteger(InOperandVal.getValueType()))
2269 assert(0 && "MATCH FAIL!");
2270
2271 // Extend/truncate to the right pointer type if needed.
2272 MVT::ValueType PtrType = TLI.getPointerTy();
2273 if (InOperandVal.getValueType() < PtrType)
2274 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2275 else if (InOperandVal.getValueType() > PtrType)
2276 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2277
2278 // Add information to the INLINEASM node to know about this input.
2279 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2280 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2281 AsmNodeOperands.push_back(InOperandVal);
2282 break;
2283 }
2284
2285 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2286
2287 // Copy the input into the appropriate registers.
2288 RegsForValue InRegs =
2289 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2290 false, true, OutputRegs, InputRegs);
2291 // FIXME: should be match fail.
2292 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2293
Evan Chenga8441262006-06-15 08:11:54 +00002294 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002295
2296 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002297 break;
2298 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002299 case InlineAsm::isClobber: {
2300 RegsForValue ClobberedRegs =
2301 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2302 OutputRegs, InputRegs);
2303 // Add the clobbered value to the operand list, so that the register
2304 // allocator is aware that the physreg got clobbered.
2305 if (!ClobberedRegs.Regs.empty())
2306 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002307 break;
2308 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002309 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002310 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002311
2312 // Finish up input operands.
2313 AsmNodeOperands[0] = Chain;
2314 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2315
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002316 Chain = DAG.getNode(ISD::INLINEASM,
2317 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002318 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002319 Flag = Chain.getValue(1);
2320
Chris Lattner6656dd12006-01-31 02:03:41 +00002321 // If this asm returns a register value, copy the result from that register
2322 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00002323 if (!RetValRegs.Regs.empty())
2324 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00002325
Chris Lattner6656dd12006-01-31 02:03:41 +00002326 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2327
2328 // Process indirect outputs, first output all of the flagged copies out of
2329 // physregs.
2330 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00002331 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00002332 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00002333 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2334 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00002335 }
2336
2337 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002338 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00002339 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Cheng786225a2006-10-05 23:01:46 +00002340 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00002341 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00002342 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00002343 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002344 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2345 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002346 DAG.setRoot(Chain);
2347}
2348
2349
Chris Lattner1c08c712005-01-07 07:47:53 +00002350void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2351 SDOperand Src = getValue(I.getOperand(0));
2352
2353 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002354
2355 if (IntPtr < Src.getValueType())
2356 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2357 else if (IntPtr > Src.getValueType())
2358 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00002359
2360 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00002361 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00002362 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2363 Src, getIntPtrConstant(ElementSize));
2364
2365 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Andersona69571c2006-05-03 01:29:57 +00002366 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00002367
2368 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00002369 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002370 DAG.getExternalSymbol("malloc", IntPtr),
2371 Args, DAG);
2372 setValue(&I, Result.first); // Pointers always fit in registers
2373 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002374}
2375
2376void SelectionDAGLowering::visitFree(FreeInst &I) {
2377 std::vector<std::pair<SDOperand, const Type*> > Args;
2378 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Andersona69571c2006-05-03 01:29:57 +00002379 TLI.getTargetData()->getIntPtrType()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002380 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00002381 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00002382 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00002383 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2384 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002385}
2386
Chris Lattner025c39b2005-08-26 20:54:47 +00002387// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2388// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2389// instructions are special in various ways, which require special support to
2390// insert. The specified MachineInstr is created but not inserted into any
2391// basic blocks, and the scheduler passes ownership of it to this method.
2392MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2393 MachineBasicBlock *MBB) {
2394 std::cerr << "If a target marks an instruction with "
2395 "'usesCustomDAGSchedInserter', it must implement "
2396 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2397 abort();
2398 return 0;
2399}
2400
Chris Lattner39ae3622005-01-09 00:00:49 +00002401void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002402 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2403 getValue(I.getOperand(1)),
2404 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00002405}
2406
2407void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002408 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2409 getValue(I.getOperand(0)),
2410 DAG.getSrcValue(I.getOperand(0)));
2411 setValue(&I, V);
2412 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002413}
2414
2415void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002416 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2417 getValue(I.getOperand(1)),
2418 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002419}
2420
2421void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00002422 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2423 getValue(I.getOperand(1)),
2424 getValue(I.getOperand(2)),
2425 DAG.getSrcValue(I.getOperand(1)),
2426 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00002427}
2428
Chris Lattnerfdfded52006-04-12 16:20:43 +00002429/// TargetLowering::LowerArguments - This is the default LowerArguments
2430/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002431/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2432/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00002433std::vector<SDOperand>
2434TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2435 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2436 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002437 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00002438 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2439 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2440
2441 // Add one result value for each formal argument.
2442 std::vector<MVT::ValueType> RetVals;
2443 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2444 MVT::ValueType VT = getValueType(I->getType());
2445
2446 switch (getTypeAction(VT)) {
2447 default: assert(0 && "Unknown type action!");
2448 case Legal:
2449 RetVals.push_back(VT);
2450 break;
2451 case Promote:
2452 RetVals.push_back(getTypeToTransformTo(VT));
2453 break;
2454 case Expand:
2455 if (VT != MVT::Vector) {
2456 // If this is a large integer, it needs to be broken up into small
2457 // integers. Figure out what the destination type is and how many small
2458 // integers it turns into.
2459 MVT::ValueType NVT = getTypeToTransformTo(VT);
2460 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2461 for (unsigned i = 0; i != NumVals; ++i)
2462 RetVals.push_back(NVT);
2463 } else {
2464 // Otherwise, this is a vector type. We only support legal vectors
2465 // right now.
2466 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2467 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002468
Chris Lattnerfdfded52006-04-12 16:20:43 +00002469 // Figure out if there is a Packed type corresponding to this Vector
2470 // type. If so, convert to the packed type.
2471 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2472 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2473 RetVals.push_back(TVT);
2474 } else {
2475 assert(0 && "Don't support illegal by-val vector arguments yet!");
2476 }
2477 }
2478 break;
2479 }
2480 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00002481
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002482 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00002483
2484 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002485 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2486 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002487 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00002488
2489 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00002490
2491 // Set up the return result vector.
2492 Ops.clear();
2493 unsigned i = 0;
2494 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2495 MVT::ValueType VT = getValueType(I->getType());
2496
2497 switch (getTypeAction(VT)) {
2498 default: assert(0 && "Unknown type action!");
2499 case Legal:
2500 Ops.push_back(SDOperand(Result, i++));
2501 break;
2502 case Promote: {
2503 SDOperand Op(Result, i++);
2504 if (MVT::isInteger(VT)) {
2505 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2506 : ISD::AssertZext;
2507 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2508 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2509 } else {
2510 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2511 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2512 }
2513 Ops.push_back(Op);
2514 break;
2515 }
2516 case Expand:
2517 if (VT != MVT::Vector) {
2518 // If this is a large integer, it needs to be reassembled from small
2519 // integers. Figure out what the source elt type is and how many small
2520 // integers it is.
2521 MVT::ValueType NVT = getTypeToTransformTo(VT);
2522 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2523 if (NumVals == 2) {
2524 SDOperand Lo = SDOperand(Result, i++);
2525 SDOperand Hi = SDOperand(Result, i++);
2526
2527 if (!isLittleEndian())
2528 std::swap(Lo, Hi);
2529
2530 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2531 } else {
2532 // Value scalarized into many values. Unimp for now.
2533 assert(0 && "Cannot expand i64 -> i16 yet!");
2534 }
2535 } else {
2536 // Otherwise, this is a vector type. We only support legal vectors
2537 // right now.
Evan Cheng020c41f2006-04-28 05:25:15 +00002538 const PackedType *PTy = cast<PackedType>(I->getType());
2539 unsigned NumElems = PTy->getNumElements();
2540 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00002541
Chris Lattnerfdfded52006-04-12 16:20:43 +00002542 // Figure out if there is a Packed type corresponding to this Vector
2543 // type. If so, convert to the packed type.
2544 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00002545 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00002546 SDOperand N = SDOperand(Result, i++);
2547 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00002548 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2549 DAG.getConstant(NumElems, MVT::i32),
2550 DAG.getValueType(getValueType(EltTy)));
2551 Ops.push_back(N);
2552 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00002553 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00002554 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00002555 }
2556 }
2557 break;
2558 }
2559 }
2560 return Ops;
2561}
2562
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002563
2564/// TargetLowering::LowerCallTo - This is the default LowerCallTo
2565/// implementation, which just inserts an ISD::CALL node, which is later custom
2566/// lowered by the target to something concrete. FIXME: When all targets are
2567/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2568std::pair<SDOperand, SDOperand>
2569TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2570 unsigned CallingConv, bool isTailCall,
2571 SDOperand Callee,
2572 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00002573 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002574 Ops.push_back(Chain); // Op#0 - Chain
2575 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2576 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2577 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2578 Ops.push_back(Callee);
2579
2580 // Handle all of the outgoing arguments.
2581 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2582 MVT::ValueType VT = getValueType(Args[i].second);
2583 SDOperand Op = Args[i].first;
Evan Chengf6d62c22006-05-25 00:55:32 +00002584 bool isSigned = Args[i].second->isSigned();
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002585 switch (getTypeAction(VT)) {
2586 default: assert(0 && "Unknown type action!");
2587 case Legal:
2588 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00002589 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002590 break;
2591 case Promote:
2592 if (MVT::isInteger(VT)) {
Evan Chengf6d62c22006-05-25 00:55:32 +00002593 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002594 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2595 } else {
2596 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2597 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2598 }
2599 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00002600 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002601 break;
2602 case Expand:
2603 if (VT != MVT::Vector) {
2604 // If this is a large integer, it needs to be broken down into small
2605 // integers. Figure out what the source elt type is and how many small
2606 // integers it is.
2607 MVT::ValueType NVT = getTypeToTransformTo(VT);
2608 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2609 if (NumVals == 2) {
2610 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2611 DAG.getConstant(0, getPointerTy()));
2612 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2613 DAG.getConstant(1, getPointerTy()));
2614 if (!isLittleEndian())
2615 std::swap(Lo, Hi);
2616
2617 Ops.push_back(Lo);
Evan Chengd61c4822006-05-26 23:13:20 +00002618 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002619 Ops.push_back(Hi);
Evan Chengd61c4822006-05-26 23:13:20 +00002620 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002621 } else {
2622 // Value scalarized into many values. Unimp for now.
2623 assert(0 && "Cannot expand i64 -> i16 yet!");
2624 }
2625 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00002626 // Otherwise, this is a vector type. We only support legal vectors
2627 // right now.
2628 const PackedType *PTy = cast<PackedType>(Args[i].second);
2629 unsigned NumElems = PTy->getNumElements();
2630 const Type *EltTy = PTy->getElementType();
2631
2632 // Figure out if there is a Packed type corresponding to this Vector
2633 // type. If so, convert to the packed type.
2634 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00002635 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2636 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2637 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2638 Ops.push_back(Op);
Evan Chengd61c4822006-05-26 23:13:20 +00002639 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00002640 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00002641 assert(0 && "Don't support illegal by-val vector call args yet!");
2642 abort();
2643 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002644 }
2645 break;
2646 }
2647 }
2648
2649 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00002650 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002651
2652 if (RetTy != Type::VoidTy) {
2653 MVT::ValueType VT = getValueType(RetTy);
2654 switch (getTypeAction(VT)) {
2655 default: assert(0 && "Unknown type action!");
2656 case Legal:
2657 RetTys.push_back(VT);
2658 break;
2659 case Promote:
2660 RetTys.push_back(getTypeToTransformTo(VT));
2661 break;
2662 case Expand:
2663 if (VT != MVT::Vector) {
2664 // If this is a large integer, it needs to be reassembled from small
2665 // integers. Figure out what the source elt type is and how many small
2666 // integers it is.
2667 MVT::ValueType NVT = getTypeToTransformTo(VT);
2668 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2669 for (unsigned i = 0; i != NumVals; ++i)
2670 RetTys.push_back(NVT);
2671 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00002672 // Otherwise, this is a vector type. We only support legal vectors
2673 // right now.
2674 const PackedType *PTy = cast<PackedType>(RetTy);
2675 unsigned NumElems = PTy->getNumElements();
2676 const Type *EltTy = PTy->getElementType();
2677
2678 // Figure out if there is a Packed type corresponding to this Vector
2679 // type. If so, convert to the packed type.
2680 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2681 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2682 RetTys.push_back(TVT);
2683 } else {
2684 assert(0 && "Don't support illegal by-val vector call results yet!");
2685 abort();
2686 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002687 }
2688 }
2689 }
2690
2691 RetTys.push_back(MVT::Other); // Always has a chain.
2692
2693 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00002694 SDOperand Res = DAG.getNode(ISD::CALL,
2695 DAG.getVTList(&RetTys[0], RetTys.size()),
2696 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002697
2698 // This returns a pair of operands. The first element is the
2699 // return value for the function (if RetTy is not VoidTy). The second
2700 // element is the outgoing token chain.
2701 SDOperand ResVal;
2702 if (RetTys.size() != 1) {
2703 MVT::ValueType VT = getValueType(RetTy);
2704 if (RetTys.size() == 2) {
2705 ResVal = Res;
2706
2707 // If this value was promoted, truncate it down.
2708 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00002709 if (VT == MVT::Vector) {
2710 // Insert a VBITCONVERT to convert from the packed result type to the
2711 // MVT::Vector type.
2712 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
2713 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
2714
2715 // Figure out if there is a Packed type corresponding to this Vector
2716 // type. If so, convert to the packed type.
2717 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2718 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00002719 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2720 // "N x PTyElementVT" MVT::Vector type.
2721 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00002722 DAG.getConstant(NumElems, MVT::i32),
2723 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00002724 } else {
2725 abort();
2726 }
2727 } else if (MVT::isInteger(VT)) {
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002728 unsigned AssertOp = RetTy->isSigned() ?
2729 ISD::AssertSext : ISD::AssertZext;
2730 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
2731 DAG.getValueType(VT));
2732 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
2733 } else {
2734 assert(MVT::isFloatingPoint(VT));
2735 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
2736 }
2737 }
2738 } else if (RetTys.size() == 3) {
2739 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
2740 Res.getValue(0), Res.getValue(1));
2741
2742 } else {
2743 assert(0 && "Case not handled yet!");
2744 }
2745 }
2746
2747 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
2748}
2749
2750
2751
Chris Lattner39ae3622005-01-09 00:00:49 +00002752// It is always conservatively correct for llvm.returnaddress and
2753// llvm.frameaddress to return 0.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00002754//
2755// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
2756// expanded to 0 if the target wants.
Chris Lattner39ae3622005-01-09 00:00:49 +00002757std::pair<SDOperand, SDOperand>
2758TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2759 unsigned Depth, SelectionDAG &DAG) {
2760 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00002761}
2762
Chris Lattner50381b62005-05-14 05:50:48 +00002763SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00002764 assert(0 && "LowerOperation not implemented for this target!");
2765 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00002766 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00002767}
2768
Nate Begeman0aed7842006-01-28 03:14:31 +00002769SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2770 SelectionDAG &DAG) {
2771 assert(0 && "CustomPromoteOperation not implemented for this target!");
2772 abort();
2773 return SDOperand();
2774}
2775
Chris Lattner39ae3622005-01-09 00:00:49 +00002776void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002777 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner39ae3622005-01-09 00:00:49 +00002778 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00002779 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00002780 setValue(&I, Result.first);
2781 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00002782}
2783
Evan Cheng74d0aa92006-02-15 21:59:04 +00002784/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00002785/// operand.
2786static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00002787 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00002788 MVT::ValueType CurVT = VT;
2789 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2790 uint64_t Val = C->getValue() & 255;
2791 unsigned Shift = 8;
2792 while (CurVT != MVT::i8) {
2793 Val = (Val << Shift) | Val;
2794 Shift <<= 1;
2795 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00002796 }
2797 return DAG.getConstant(Val, VT);
2798 } else {
2799 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2800 unsigned Shift = 8;
2801 while (CurVT != MVT::i8) {
2802 Value =
2803 DAG.getNode(ISD::OR, VT,
2804 DAG.getNode(ISD::SHL, VT, Value,
2805 DAG.getConstant(Shift, MVT::i8)), Value);
2806 Shift <<= 1;
2807 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00002808 }
2809
2810 return Value;
2811 }
2812}
2813
Evan Cheng74d0aa92006-02-15 21:59:04 +00002814/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2815/// used when a memcpy is turned into a memset when the source is a constant
2816/// string ptr.
2817static SDOperand getMemsetStringVal(MVT::ValueType VT,
2818 SelectionDAG &DAG, TargetLowering &TLI,
2819 std::string &Str, unsigned Offset) {
2820 MVT::ValueType CurVT = VT;
2821 uint64_t Val = 0;
2822 unsigned MSB = getSizeInBits(VT) / 8;
2823 if (TLI.isLittleEndian())
2824 Offset = Offset + MSB - 1;
2825 for (unsigned i = 0; i != MSB; ++i) {
2826 Val = (Val << 8) | Str[Offset];
2827 Offset += TLI.isLittleEndian() ? -1 : 1;
2828 }
2829 return DAG.getConstant(Val, VT);
2830}
2831
Evan Cheng1db92f92006-02-14 08:22:34 +00002832/// getMemBasePlusOffset - Returns base and offset node for the
2833static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2834 SelectionDAG &DAG, TargetLowering &TLI) {
2835 MVT::ValueType VT = Base.getValueType();
2836 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2837}
2838
Evan Chengc4f8eee2006-02-14 20:12:38 +00002839/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00002840/// to replace the memset / memcpy is below the threshold. It also returns the
2841/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00002842static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2843 unsigned Limit, uint64_t Size,
2844 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00002845 MVT::ValueType VT;
2846
2847 if (TLI.allowsUnalignedMemoryAccesses()) {
2848 VT = MVT::i64;
2849 } else {
2850 switch (Align & 7) {
2851 case 0:
2852 VT = MVT::i64;
2853 break;
2854 case 4:
2855 VT = MVT::i32;
2856 break;
2857 case 2:
2858 VT = MVT::i16;
2859 break;
2860 default:
2861 VT = MVT::i8;
2862 break;
2863 }
2864 }
2865
Evan Cheng80e89d72006-02-14 09:11:59 +00002866 MVT::ValueType LVT = MVT::i64;
2867 while (!TLI.isTypeLegal(LVT))
2868 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2869 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00002870
Evan Cheng80e89d72006-02-14 09:11:59 +00002871 if (VT > LVT)
2872 VT = LVT;
2873
Evan Chengdea72452006-02-14 23:05:54 +00002874 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00002875 while (Size != 0) {
2876 unsigned VTSize = getSizeInBits(VT) / 8;
2877 while (VTSize > Size) {
2878 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00002879 VTSize >>= 1;
2880 }
Evan Cheng80e89d72006-02-14 09:11:59 +00002881 assert(MVT::isInteger(VT));
2882
2883 if (++NumMemOps > Limit)
2884 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00002885 MemOps.push_back(VT);
2886 Size -= VTSize;
2887 }
Evan Cheng80e89d72006-02-14 09:11:59 +00002888
2889 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00002890}
2891
Chris Lattner7041ee32005-01-11 05:56:49 +00002892void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00002893 SDOperand Op1 = getValue(I.getOperand(1));
2894 SDOperand Op2 = getValue(I.getOperand(2));
2895 SDOperand Op3 = getValue(I.getOperand(3));
2896 SDOperand Op4 = getValue(I.getOperand(4));
2897 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2898 if (Align == 0) Align = 1;
2899
2900 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2901 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00002902
2903 // Expand memset / memcpy to a series of load / store ops
2904 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002905 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00002906 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00002907 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00002908 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00002909 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2910 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00002911 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00002912 unsigned Offset = 0;
2913 for (unsigned i = 0; i < NumMemOps; i++) {
2914 MVT::ValueType VT = MemOps[i];
2915 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00002916 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00002917 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00002918 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00002919 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00002920 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00002921 Offset += VTSize;
2922 }
Evan Cheng1db92f92006-02-14 08:22:34 +00002923 }
Evan Chengc080d6f2006-02-15 01:54:51 +00002924 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00002925 }
Evan Chengc080d6f2006-02-15 01:54:51 +00002926 case ISD::MEMCPY: {
2927 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2928 Size->getValue(), Align, TLI)) {
2929 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00002930 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00002931 GlobalAddressSDNode *G = NULL;
2932 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00002933 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00002934
2935 if (Op2.getOpcode() == ISD::GlobalAddress)
2936 G = cast<GlobalAddressSDNode>(Op2);
2937 else if (Op2.getOpcode() == ISD::ADD &&
2938 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2939 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2940 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00002941 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00002942 }
2943 if (G) {
2944 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengcffbb512006-02-16 23:11:42 +00002945 if (GV) {
Evan Cheng09371032006-03-10 23:52:03 +00002946 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00002947 if (!Str.empty()) {
2948 CopyFromStr = true;
2949 SrcOff += SrcDelta;
2950 }
2951 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00002952 }
2953
Evan Chengc080d6f2006-02-15 01:54:51 +00002954 for (unsigned i = 0; i < NumMemOps; i++) {
2955 MVT::ValueType VT = MemOps[i];
2956 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00002957 SDOperand Value, Chain, Store;
2958
Evan Chengcffbb512006-02-16 23:11:42 +00002959 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00002960 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2961 Chain = getRoot();
2962 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00002963 DAG.getStore(Chain, Value,
2964 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00002965 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00002966 } else {
2967 Value = DAG.getLoad(VT, getRoot(),
2968 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00002969 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00002970 Chain = Value.getValue(1);
2971 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00002972 DAG.getStore(Chain, Value,
2973 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00002974 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00002975 }
Evan Chengc080d6f2006-02-15 01:54:51 +00002976 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00002977 SrcOff += VTSize;
2978 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00002979 }
2980 }
2981 break;
2982 }
2983 }
2984
2985 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002986 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
2987 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00002988 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00002989 }
2990 }
2991
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002992 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00002993}
2994
Chris Lattner7041ee32005-01-11 05:56:49 +00002995//===----------------------------------------------------------------------===//
2996// SelectionDAGISel code
2997//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00002998
2999unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3000 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3001}
3002
Chris Lattner495a0b52005-08-17 06:37:43 +00003003void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00003004 // FIXME: we only modify the CFG to split critical edges. This
3005 // updates dom and loop info.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003006 AU.addRequired<AliasAnalysis>();
Chris Lattner495a0b52005-08-17 06:37:43 +00003007}
Chris Lattner1c08c712005-01-07 07:47:53 +00003008
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003009
Chris Lattner90323642006-05-05 21:17:49 +00003010/// OptimizeNoopCopyExpression - We have determined that the specified cast
3011/// instruction is a noop copy (e.g. it's casting from one pointer type to
3012/// another, int->uint, or int->sbyte on PPC.
3013///
3014/// Return true if any changes are made.
3015static bool OptimizeNoopCopyExpression(CastInst *CI) {
3016 BasicBlock *DefBB = CI->getParent();
3017
3018 /// InsertedCasts - Only insert a cast in each block once.
3019 std::map<BasicBlock*, CastInst*> InsertedCasts;
3020
3021 bool MadeChange = false;
3022 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3023 UI != E; ) {
3024 Use &TheUse = UI.getUse();
3025 Instruction *User = cast<Instruction>(*UI);
3026
3027 // Figure out which BB this cast is used in. For PHI's this is the
3028 // appropriate predecessor block.
3029 BasicBlock *UserBB = User->getParent();
3030 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3031 unsigned OpVal = UI.getOperandNo()/2;
3032 UserBB = PN->getIncomingBlock(OpVal);
3033 }
3034
3035 // Preincrement use iterator so we don't invalidate it.
3036 ++UI;
3037
3038 // If this user is in the same block as the cast, don't change the cast.
3039 if (UserBB == DefBB) continue;
3040
3041 // If we have already inserted a cast into this block, use it.
3042 CastInst *&InsertedCast = InsertedCasts[UserBB];
3043
3044 if (!InsertedCast) {
3045 BasicBlock::iterator InsertPt = UserBB->begin();
3046 while (isa<PHINode>(InsertPt)) ++InsertPt;
3047
3048 InsertedCast =
3049 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3050 MadeChange = true;
3051 }
3052
3053 // Replace a use of the cast with a use of the new casat.
3054 TheUse = InsertedCast;
3055 }
3056
3057 // If we removed all uses, nuke the cast.
3058 if (CI->use_empty())
3059 CI->eraseFromParent();
3060
3061 return MadeChange;
3062}
3063
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003064/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3065/// casting to the type of GEPI.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003066static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3067 Instruction *GEPI, Value *Ptr,
3068 Value *PtrOffset) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003069 if (V) return V; // Already computed.
3070
3071 BasicBlock::iterator InsertPt;
3072 if (BB == GEPI->getParent()) {
3073 // If insert into the GEP's block, insert right after the GEP.
3074 InsertPt = GEPI;
3075 ++InsertPt;
3076 } else {
3077 // Otherwise, insert at the top of BB, after any PHI nodes
3078 InsertPt = BB->begin();
3079 while (isa<PHINode>(InsertPt)) ++InsertPt;
3080 }
3081
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003082 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3083 // BB so that there is only one value live across basic blocks (the cast
3084 // operand).
3085 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3086 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3087 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3088
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003089 // Add the offset, cast it to the right type.
3090 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Chris Lattnerf0df8822006-05-06 09:10:37 +00003091 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003092}
3093
Chris Lattner90323642006-05-05 21:17:49 +00003094/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3095/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3096/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3097/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3098/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3099/// the constant add into a load or store instruction. Additionally, if a user
3100/// is a pointer-pointer cast, we look through it to find its users.
3101static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3102 Constant *PtrOffset, BasicBlock *DefBB,
3103 GetElementPtrInst *GEPI,
Chris Lattnerf0df8822006-05-06 09:10:37 +00003104 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner90323642006-05-05 21:17:49 +00003105 while (!RepPtr->use_empty()) {
3106 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7e598092006-05-05 01:04:50 +00003107
Chris Lattner90323642006-05-05 21:17:49 +00003108 // If the user is a Pointer-Pointer cast, recurse.
3109 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3110 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7e598092006-05-05 01:04:50 +00003111
Chris Lattner90323642006-05-05 21:17:49 +00003112 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3113 // could invalidate an iterator.
3114 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3115 continue;
Chris Lattner7e598092006-05-05 01:04:50 +00003116 }
3117
Chris Lattner90323642006-05-05 21:17:49 +00003118 // If this is a load of the pointer, or a store through the pointer, emit
3119 // the increment into the load/store block.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003120 Instruction *NewVal;
Chris Lattner90323642006-05-05 21:17:49 +00003121 if (isa<LoadInst>(User) ||
3122 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3123 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3124 User->getParent(), GEPI,
3125 Ptr, PtrOffset);
3126 } else {
3127 // If this use is not foldable into the addressing mode, use a version
3128 // emitted in the GEP block.
3129 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3130 Ptr, PtrOffset);
3131 }
3132
Chris Lattnerf0df8822006-05-06 09:10:37 +00003133 if (GEPI->getType() != RepPtr->getType()) {
3134 BasicBlock::iterator IP = NewVal;
3135 ++IP;
3136 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3137 }
Chris Lattner90323642006-05-05 21:17:49 +00003138 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7e598092006-05-05 01:04:50 +00003139 }
3140}
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003141
Chris Lattner90323642006-05-05 21:17:49 +00003142
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003143/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3144/// selection, we want to be a bit careful about some things. In particular, if
3145/// we have a GEP instruction that is used in a different block than it is
3146/// defined, the addressing expression of the GEP cannot be folded into loads or
3147/// stores that use it. In this case, decompose the GEP and move constant
3148/// indices into blocks that use it.
Chris Lattner90323642006-05-05 21:17:49 +00003149static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Andersona69571c2006-05-03 01:29:57 +00003150 const TargetData *TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003151 // If this GEP is only used inside the block it is defined in, there is no
3152 // need to rewrite it.
3153 bool isUsedOutsideDefBB = false;
3154 BasicBlock *DefBB = GEPI->getParent();
3155 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3156 UI != E; ++UI) {
3157 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3158 isUsedOutsideDefBB = true;
3159 break;
3160 }
3161 }
Chris Lattner90323642006-05-05 21:17:49 +00003162 if (!isUsedOutsideDefBB) return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003163
3164 // If this GEP has no non-zero constant indices, there is nothing we can do,
3165 // ignore it.
3166 bool hasConstantIndex = false;
Chris Lattner90323642006-05-05 21:17:49 +00003167 bool hasVariableIndex = false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003168 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3169 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner90323642006-05-05 21:17:49 +00003170 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003171 if (CI->getZExtValue()) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003172 hasConstantIndex = true;
3173 break;
3174 }
Chris Lattner90323642006-05-05 21:17:49 +00003175 } else {
3176 hasVariableIndex = true;
3177 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003178 }
Chris Lattner90323642006-05-05 21:17:49 +00003179
3180 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3181 if (!hasConstantIndex && !hasVariableIndex) {
3182 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3183 GEPI->getName(), GEPI);
3184 GEPI->replaceAllUsesWith(NC);
3185 GEPI->eraseFromParent();
3186 return true;
3187 }
3188
Chris Lattner3802c252005-12-11 09:05:13 +00003189 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner90323642006-05-05 21:17:49 +00003190 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3191 return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003192
3193 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3194 // constant offset (which we now know is non-zero) and deal with it later.
3195 uint64_t ConstantOffset = 0;
Owen Andersona69571c2006-05-03 01:29:57 +00003196 const Type *UIntPtrTy = TD->getIntPtrType();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003197 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3198 const Type *Ty = GEPI->getOperand(0)->getType();
3199
3200 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3201 E = GEPI->op_end(); OI != E; ++OI) {
3202 Value *Idx = *OI;
3203 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003204 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003205 if (Field)
Owen Andersona69571c2006-05-03 01:29:57 +00003206 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003207 Ty = StTy->getElementType(Field);
3208 } else {
3209 Ty = cast<SequentialType>(Ty)->getElementType();
3210
3211 // Handle constant subscripts.
3212 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003213 if (CI->getZExtValue() == 0) continue;
3214 if (CI->getType()->isSigned())
3215 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003216 else
Reid Spencerb83eb642006-10-20 07:07:24 +00003217 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003218 continue;
3219 }
3220
3221 // Ptr = Ptr + Idx * ElementSize;
3222
3223 // Cast Idx to UIntPtrTy if needed.
3224 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3225
Owen Andersona69571c2006-05-03 01:29:57 +00003226 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003227 // Mask off bits that should not be set.
3228 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003229 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003230
3231 // Multiply by the element size and add to the base.
3232 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3233 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3234 }
3235 }
3236
3237 // Make sure that the offset fits in uintptr_t.
3238 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003239 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003240
3241 // Okay, we have now emitted all of the variable index parts to the BB that
3242 // the GEP is defined in. Loop over all of the using instructions, inserting
3243 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003244 // instruction to use the newly computed value, making GEPI dead. When the
3245 // user is a load or store instruction address, we emit the add into the user
3246 // block, otherwise we use a canonical version right next to the gep (these
3247 // won't be foldable as addresses, so we might as well share the computation).
3248
Chris Lattnerf0df8822006-05-06 09:10:37 +00003249 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner90323642006-05-05 21:17:49 +00003250 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003251
3252 // Finally, the GEP is dead, remove it.
3253 GEPI->eraseFromParent();
Chris Lattner90323642006-05-05 21:17:49 +00003254
3255 return true;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003256}
3257
Chris Lattner57f9a432006-09-28 06:17:10 +00003258/// SplitCritEdgesForPHIConstants - If this block has any PHI nodes with
3259/// constant operands, and if any of the edges feeding the PHI node are
3260/// critical, split them so that the assignments of a constant to a register
3261/// will not be executed on a path that isn't relevant.
3262void SelectionDAGISel::SplitCritEdgesForPHIConstants(BasicBlock *BB) {
Chris Lattner75548062006-10-11 03:58:02 +00003263 // The most common case is that this is a PHI node with two incoming
3264 // successors handle this case efficiently, because it is simple.
3265 PHINode *PN = cast<PHINode>(BB->begin());
3266 if (PN->getNumIncomingValues() == 2) {
3267 // If neither edge is critical, we never need to split.
3268 if (PN->getIncomingBlock(0)->getTerminator()->getNumSuccessors() == 1 &&
3269 PN->getIncomingBlock(1)->getTerminator()->getNumSuccessors() == 1)
3270 return;
3271
3272 BasicBlock::iterator BBI = BB->begin();
3273 while ((PN = dyn_cast<PHINode>(BBI++))) {
3274 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3275 if (isa<Constant>(PN->getIncomingValue(i)))
3276 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3277 }
3278 return;
3279 }
3280
3281 // Otherwise, things are a bit trickier.
3282
3283 // BE SMART HERE.
3284
Chris Lattner57f9a432006-09-28 06:17:10 +00003285 BasicBlock::iterator BBI = BB->begin();
3286 while ((PN = dyn_cast<PHINode>(BBI++))) {
3287 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3288 if (isa<Constant>(PN->getIncomingValue(i)))
3289 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3290 }
3291}
3292
3293
Chris Lattner1c08c712005-01-07 07:47:53 +00003294bool SelectionDAGISel::runOnFunction(Function &Fn) {
3295 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3296 RegMap = MF.getSSARegMap();
3297 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3298
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003299 // First, split all critical edges for PHI nodes with incoming values that are
3300 // constants, this way the load of the constant into a vreg will not be placed
3301 // into MBBs that are used some other way.
3302 //
Chris Lattner7e598092006-05-05 01:04:50 +00003303 // In this pass we also look for GEP and cast instructions that are used
3304 // across basic blocks and rewrite them to improve basic-block-at-a-time
3305 // selection.
3306 //
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003307 //
Chris Lattner90323642006-05-05 21:17:49 +00003308 bool MadeChange = true;
3309 while (MadeChange) {
3310 MadeChange = false;
Chris Lattner36b708f2005-08-18 17:35:14 +00003311 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattner57f9a432006-09-28 06:17:10 +00003312 // If this block has any PHI nodes with constant operands, and if any of the
3313 // edges feeding the PHI node are critical, split them.
3314 if (isa<PHINode>(BB->begin()))
3315 SplitCritEdgesForPHIConstants(BB);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003316
Chris Lattner57f9a432006-09-28 06:17:10 +00003317 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7e598092006-05-05 01:04:50 +00003318 Instruction *I = BBI++;
3319 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner90323642006-05-05 21:17:49 +00003320 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7e598092006-05-05 01:04:50 +00003321 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerc970f062006-09-13 06:02:42 +00003322 // If the source of the cast is a constant, then this should have
3323 // already been constant folded. The only reason NOT to constant fold
3324 // it is if something (e.g. LSR) was careful to place the constant
3325 // evaluation in a block other than then one that uses it (e.g. to hoist
3326 // the address of globals out of a loop). If this is the case, we don't
3327 // want to forward-subst the cast.
3328 if (isa<Constant>(CI->getOperand(0)))
3329 continue;
3330
Chris Lattner7e598092006-05-05 01:04:50 +00003331 // If this is a noop copy, sink it into user blocks to reduce the number
3332 // of virtual registers that must be created and coallesced.
3333 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3334 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3335
3336 // This is an fp<->int conversion?
3337 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3338 continue;
3339
3340 // If this is an extension, it will be a zero or sign extension, which
3341 // isn't a noop.
3342 if (SrcVT < DstVT) continue;
3343
3344 // If these values will be promoted, find out what they will be promoted
3345 // to. This helps us consider truncates on PPC as noop copies when they
3346 // are.
3347 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3348 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3349 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3350 DstVT = TLI.getTypeToTransformTo(DstVT);
3351
3352 // If, after promotion, these are the same types, this is a noop copy.
3353 if (SrcVT == DstVT)
Chris Lattner90323642006-05-05 21:17:49 +00003354 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7e598092006-05-05 01:04:50 +00003355 }
3356 }
Chris Lattner36b708f2005-08-18 17:35:14 +00003357 }
Chris Lattner90323642006-05-05 21:17:49 +00003358 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003359
Chris Lattner1c08c712005-01-07 07:47:53 +00003360 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3361
3362 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3363 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00003364
Chris Lattner1c08c712005-01-07 07:47:53 +00003365 return true;
3366}
3367
3368
Chris Lattnerddb870b2005-01-13 17:59:43 +00003369SDOperand SelectionDAGISel::
3370CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00003371 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00003372 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003373 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00003374 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003375
3376 // If this type is not legal, we must make sure to not create an invalid
3377 // register use.
3378 MVT::ValueType SrcVT = Op.getValueType();
3379 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3380 SelectionDAG &DAG = SDL.DAG;
3381 if (SrcVT == DestVT) {
3382 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003383 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00003384 // Handle copies from generic vectors to registers.
3385 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3386 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3387 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00003388
Chris Lattner70c2a612006-03-31 02:06:56 +00003389 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3390 // MVT::Vector type.
3391 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3392 DAG.getConstant(NE, MVT::i32),
3393 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00003394
Chris Lattner70c2a612006-03-31 02:06:56 +00003395 // Loop over all of the elements of the resultant vector,
3396 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3397 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003398 SmallVector<SDOperand, 8> OutChains;
Chris Lattner70c2a612006-03-31 02:06:56 +00003399 SDOperand Root = SDL.getRoot();
3400 for (unsigned i = 0; i != NE; ++i) {
3401 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003402 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003403 if (PTyElementVT == PTyLegalElementVT) {
3404 // Elements are legal.
3405 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3406 } else if (PTyLegalElementVT > PTyElementVT) {
3407 // Elements are promoted.
3408 if (MVT::isFloatingPoint(PTyLegalElementVT))
3409 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3410 else
3411 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3412 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3413 } else {
3414 // Elements are expanded.
3415 // The src value is expanded into multiple registers.
3416 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003417 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003418 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00003419 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00003420 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3421 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3422 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00003423 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003424 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3425 &OutChains[0], OutChains.size());
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003426 } else if (SrcVT < DestVT) {
3427 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00003428 if (MVT::isFloatingPoint(SrcVT))
3429 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3430 else
Chris Lattnerfab08872005-09-02 00:19:37 +00003431 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003432 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
3433 } else {
3434 // The src value is expanded into multiple registers.
3435 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003436 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003437 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00003438 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00003439 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
3440 return DAG.getCopyToReg(Op, Reg+1, Hi);
3441 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003442}
3443
Chris Lattner068a81e2005-01-17 17:15:02 +00003444void SelectionDAGISel::
3445LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3446 std::vector<SDOperand> &UnorderedChains) {
3447 // If this is the entry block, emit arguments.
3448 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00003449 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00003450 SDOperand OldRoot = SDL.DAG.getRoot();
3451 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00003452
Chris Lattnerbf209482005-10-30 19:42:35 +00003453 unsigned a = 0;
3454 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3455 AI != E; ++AI, ++a)
3456 if (!AI->use_empty()) {
3457 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00003458
Chris Lattnerbf209482005-10-30 19:42:35 +00003459 // If this argument is live outside of the entry block, insert a copy from
3460 // whereever we got it to the vreg that other BB's will reference it as.
3461 if (FuncInfo.ValueMap.count(AI)) {
3462 SDOperand Copy =
3463 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
3464 UnorderedChains.push_back(Copy);
3465 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00003466 }
Chris Lattnerbf209482005-10-30 19:42:35 +00003467
Chris Lattnerbf209482005-10-30 19:42:35 +00003468 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00003469 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00003470 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00003471}
3472
Chris Lattner1c08c712005-01-07 07:47:53 +00003473void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3474 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00003475 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00003476 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00003477
3478 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00003479
Chris Lattnerbf209482005-10-30 19:42:35 +00003480 // Lower any arguments needed in this block if this is the entry block.
3481 if (LLVMBB == &LLVMBB->getParent()->front())
3482 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00003483
3484 BB = FuncInfo.MBBMap[LLVMBB];
3485 SDL.setCurrentBasicBlock(BB);
3486
3487 // Lower all of the non-terminator instructions.
3488 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3489 I != E; ++I)
3490 SDL.visit(*I);
Nate Begemanf15485a2006-03-27 01:32:24 +00003491
Chris Lattner1c08c712005-01-07 07:47:53 +00003492 // Ensure that all instructions which are used outside of their defining
3493 // blocks are available as virtual registers.
3494 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00003495 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00003496 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00003497 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00003498 UnorderedChains.push_back(
3499 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00003500 }
3501
3502 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3503 // ensure constants are generated when needed. Remember the virtual registers
3504 // that need to be added to the Machine PHI nodes as input. We cannot just
3505 // directly add them, because expansion might result in multiple MBB's for one
3506 // BB. As such, the start of the BB might correspond to a different MBB than
3507 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00003508 //
Chris Lattner1c08c712005-01-07 07:47:53 +00003509
3510 // Emit constants only once even if used by multiple PHI nodes.
3511 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003512
Chris Lattner1c08c712005-01-07 07:47:53 +00003513 // Check successor nodes PHI nodes that expect a constant to be available from
3514 // this block.
3515 TerminatorInst *TI = LLVMBB->getTerminator();
3516 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3517 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003518 if (!isa<PHINode>(SuccBB->begin())) continue;
3519
Chris Lattner1c08c712005-01-07 07:47:53 +00003520 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
3521 PHINode *PN;
3522
3523 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3524 // nodes and Machine PHI nodes, but the incoming operands have not been
3525 // emitted yet.
3526 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00003527 (PN = dyn_cast<PHINode>(I)); ++I)
3528 if (!PN->use_empty()) {
3529 unsigned Reg;
3530 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3531 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3532 unsigned &RegOut = ConstantsOut[C];
3533 if (RegOut == 0) {
3534 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00003535 UnorderedChains.push_back(
3536 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00003537 }
3538 Reg = RegOut;
3539 } else {
3540 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00003541 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00003542 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00003543 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3544 "Didn't codegen value into a register!??");
3545 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00003546 UnorderedChains.push_back(
3547 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00003548 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003549 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003550
Chris Lattnerf44fd882005-01-07 21:34:19 +00003551 // Remember that this register needs to added to the machine PHI node as
3552 // the input for this MBB.
Chris Lattner7e021512006-03-31 02:12:18 +00003553 MVT::ValueType VT = TLI.getValueType(PN->getType());
3554 unsigned NumElements;
3555 if (VT != MVT::Vector)
3556 NumElements = TLI.getNumElements(VT);
3557 else {
3558 MVT::ValueType VT1,VT2;
3559 NumElements =
3560 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3561 VT1, VT2);
3562 }
Chris Lattnerf44fd882005-01-07 21:34:19 +00003563 for (unsigned i = 0, e = NumElements; i != e; ++i)
3564 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00003565 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003566 }
3567 ConstantsOut.clear();
3568
Chris Lattnerddb870b2005-01-13 17:59:43 +00003569 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00003570 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00003571 SDOperand Root = SDL.getRoot();
3572 if (Root.getOpcode() != ISD::EntryToken) {
3573 unsigned i = 0, e = UnorderedChains.size();
3574 for (; i != e; ++i) {
3575 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3576 if (UnorderedChains[i].Val->getOperand(0) == Root)
3577 break; // Don't add the root if we already indirectly depend on it.
3578 }
3579
3580 if (i == e)
3581 UnorderedChains.push_back(Root);
3582 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003583 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3584 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00003585 }
3586
Chris Lattner1c08c712005-01-07 07:47:53 +00003587 // Lower the terminator after the copies are emitted.
3588 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00003589
Nate Begemanf15485a2006-03-27 01:32:24 +00003590 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00003591 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00003592 SwitchCases.clear();
3593 SwitchCases = SDL.SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +00003594 JT = SDL.JT;
Nate Begemanf15485a2006-03-27 01:32:24 +00003595
Chris Lattnera651cf62005-01-17 19:43:36 +00003596 // Make sure the root of the DAG is up-to-date.
3597 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00003598}
3599
Nate Begemanf15485a2006-03-27 01:32:24 +00003600void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003601 // Get alias analysis for load/store combining.
3602 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3603
Chris Lattneraf21d552005-10-10 16:47:10 +00003604 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003605 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00003606
Chris Lattner1c08c712005-01-07 07:47:53 +00003607 DEBUG(std::cerr << "Lowered selection DAG:\n");
3608 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00003609
Chris Lattner1c08c712005-01-07 07:47:53 +00003610 // Second step, hack on the DAG until it only uses operations and types that
3611 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00003612 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00003613
Chris Lattner1c08c712005-01-07 07:47:53 +00003614 DEBUG(std::cerr << "Legalized selection DAG:\n");
3615 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00003616
Chris Lattneraf21d552005-10-10 16:47:10 +00003617 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003618 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00003619
Evan Chenga9c20912006-01-21 02:32:06 +00003620 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00003621
Chris Lattnera33ef482005-03-30 01:10:47 +00003622 // Third, instruction select all of the operations to machine code, adding the
3623 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00003624 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00003625
Chris Lattner1c08c712005-01-07 07:47:53 +00003626 DEBUG(std::cerr << "Selected machine code:\n");
3627 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00003628}
Chris Lattner1c08c712005-01-07 07:47:53 +00003629
Nate Begemanf15485a2006-03-27 01:32:24 +00003630void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3631 FunctionLoweringInfo &FuncInfo) {
3632 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3633 {
3634 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3635 CurDAG = &DAG;
3636
3637 // First step, lower LLVM code to some DAG. This DAG may use operations and
3638 // types that are not supported by the target.
3639 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3640
3641 // Second step, emit the lowered DAG as machine code.
3642 CodeGenAndEmitDAG(DAG);
3643 }
3644
Chris Lattnera33ef482005-03-30 01:10:47 +00003645 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00003646 // PHI nodes in successors.
Nate Begeman37efe672006-04-22 18:53:45 +00003647 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemanf15485a2006-03-27 01:32:24 +00003648 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3649 MachineInstr *PHI = PHINodesToUpdate[i].first;
3650 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3651 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00003652 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00003653 PHI->addMachineBasicBlockOperand(BB);
3654 }
3655 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00003656 }
Nate Begemanf15485a2006-03-27 01:32:24 +00003657
Nate Begeman9453eea2006-04-23 06:26:20 +00003658 // If the JumpTable record is filled in, then we need to emit a jump table.
3659 // Updating the PHI nodes is tricky in this case, since we need to determine
3660 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman37efe672006-04-22 18:53:45 +00003661 if (JT.Reg) {
3662 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3663 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3664 CurDAG = &SDAG;
3665 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman9453eea2006-04-23 06:26:20 +00003666 MachineBasicBlock *RangeBB = BB;
Nate Begeman37efe672006-04-22 18:53:45 +00003667 // Set the current basic block to the mbb we wish to insert the code into
3668 BB = JT.MBB;
3669 SDL.setCurrentBasicBlock(BB);
3670 // Emit the code
3671 SDL.visitJumpTable(JT);
3672 SDAG.setRoot(SDL.getRoot());
3673 CodeGenAndEmitDAG(SDAG);
3674 // Update PHI Nodes
3675 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3676 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3677 MachineBasicBlock *PHIBB = PHI->getParent();
3678 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3679 "This is not a machine PHI node that we are updating!");
Nate Begemanf4360a42006-05-03 03:48:02 +00003680 if (PHIBB == JT.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00003681 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00003682 PHI->addMachineBasicBlockOperand(RangeBB);
3683 }
3684 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00003685 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00003686 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00003687 }
3688 }
3689 return;
3690 }
3691
Chris Lattnerb2e806e2006-10-22 23:00:53 +00003692 // If the switch block involved a branch to one of the actual successors, we
3693 // need to update PHI nodes in that block.
3694 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3695 MachineInstr *PHI = PHINodesToUpdate[i].first;
3696 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3697 "This is not a machine PHI node that we are updating!");
3698 if (BB->isSuccessor(PHI->getParent())) {
3699 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
3700 PHI->addMachineBasicBlockOperand(BB);
3701 }
3702 }
3703
Nate Begemanf15485a2006-03-27 01:32:24 +00003704 // If we generated any switch lowering information, build and codegen any
3705 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003706 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemanf15485a2006-03-27 01:32:24 +00003707 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3708 CurDAG = &SDAG;
3709 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003710
Nate Begemanf15485a2006-03-27 01:32:24 +00003711 // Set the current basic block to the mbb we wish to insert the code into
3712 BB = SwitchCases[i].ThisBB;
3713 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003714
Nate Begemanf15485a2006-03-27 01:32:24 +00003715 // Emit the code
3716 SDL.visitSwitchCase(SwitchCases[i]);
3717 SDAG.setRoot(SDL.getRoot());
3718 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003719
3720 // Handle any PHI nodes in successors of this chunk, as if we were coming
3721 // from the original BB before switch expansion. Note that PHI nodes can
3722 // occur multiple times in PHINodesToUpdate. We have to be very careful to
3723 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00003724 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003725 for (MachineBasicBlock::iterator Phi = BB->begin();
3726 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
3727 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
3728 for (unsigned pn = 0; ; ++pn) {
3729 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
3730 if (PHINodesToUpdate[pn].first == Phi) {
3731 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
3732 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
3733 break;
3734 }
3735 }
Nate Begemanf15485a2006-03-27 01:32:24 +00003736 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003737
3738 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00003739 if (BB == SwitchCases[i].FalseBB)
3740 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00003741
3742 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00003743 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00003744 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00003745 }
Chris Lattner57ab6592006-10-24 17:57:59 +00003746 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00003747 }
Chris Lattner1c08c712005-01-07 07:47:53 +00003748}
Evan Chenga9c20912006-01-21 02:32:06 +00003749
Jim Laskey13ec7022006-08-01 14:21:23 +00003750
Evan Chenga9c20912006-01-21 02:32:06 +00003751//===----------------------------------------------------------------------===//
3752/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3753/// target node in the graph.
3754void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3755 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00003756
Jim Laskeyeb577ba2006-08-02 12:30:23 +00003757 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00003758
3759 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00003760 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00003761 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00003762 }
Jim Laskey13ec7022006-08-01 14:21:23 +00003763
Jim Laskey9ff542f2006-08-01 18:29:48 +00003764 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00003765 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00003766 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00003767}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00003768
Chris Lattner03fc53c2006-03-06 00:22:00 +00003769
Jim Laskey9ff542f2006-08-01 18:29:48 +00003770HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3771 return new HazardRecognizer();
3772}
3773
Chris Lattner75548062006-10-11 03:58:02 +00003774//===----------------------------------------------------------------------===//
3775// Helper functions used by the generated instruction selector.
3776//===----------------------------------------------------------------------===//
3777// Calls to these methods are generated by tblgen.
3778
3779/// CheckAndMask - The isel is trying to match something like (and X, 255). If
3780/// the dag combiner simplified the 255, we still want to match. RHS is the
3781/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
3782/// specified in the .td file (e.g. 255).
3783bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
3784 int64_t DesiredMaskS) {
3785 uint64_t ActualMask = RHS->getValue();
3786 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
3787
3788 // If the actual mask exactly matches, success!
3789 if (ActualMask == DesiredMask)
3790 return true;
3791
3792 // If the actual AND mask is allowing unallowed bits, this doesn't match.
3793 if (ActualMask & ~DesiredMask)
3794 return false;
3795
3796 // Otherwise, the DAG Combiner may have proven that the value coming in is
3797 // either already zero or is not demanded. Check for known zero input bits.
3798 uint64_t NeededMask = DesiredMask & ~ActualMask;
3799 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
3800 return true;
3801
3802 // TODO: check to see if missing bits are just not demanded.
3803
3804 // Otherwise, this pattern doesn't match.
3805 return false;
3806}
3807
3808/// CheckOrMask - The isel is trying to match something like (or X, 255). If
3809/// the dag combiner simplified the 255, we still want to match. RHS is the
3810/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
3811/// specified in the .td file (e.g. 255).
3812bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
3813 int64_t DesiredMaskS) {
3814 uint64_t ActualMask = RHS->getValue();
3815 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
3816
3817 // If the actual mask exactly matches, success!
3818 if (ActualMask == DesiredMask)
3819 return true;
3820
3821 // If the actual AND mask is allowing unallowed bits, this doesn't match.
3822 if (ActualMask & ~DesiredMask)
3823 return false;
3824
3825 // Otherwise, the DAG Combiner may have proven that the value coming in is
3826 // either already zero or is not demanded. Check for known zero input bits.
3827 uint64_t NeededMask = DesiredMask & ~ActualMask;
3828
3829 uint64_t KnownZero, KnownOne;
3830 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
3831
3832 // If all the missing bits in the or are already known to be set, match!
3833 if ((NeededMask & KnownOne) == NeededMask)
3834 return true;
3835
3836 // TODO: check to see if missing bits are just not demanded.
3837
3838 // Otherwise, this pattern doesn't match.
3839 return false;
3840}
3841
Jim Laskey9ff542f2006-08-01 18:29:48 +00003842
Chris Lattner0e43f2b2006-02-24 02:13:54 +00003843/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
3844/// by tblgen. Others should not call it.
3845void SelectionDAGISel::
3846SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
3847 std::vector<SDOperand> InOps;
3848 std::swap(InOps, Ops);
3849
3850 Ops.push_back(InOps[0]); // input chain.
3851 Ops.push_back(InOps[1]); // input asm string.
3852
Chris Lattner0e43f2b2006-02-24 02:13:54 +00003853 unsigned i = 2, e = InOps.size();
3854 if (InOps[e-1].getValueType() == MVT::Flag)
3855 --e; // Don't process a flag operand if it is here.
3856
3857 while (i != e) {
3858 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
3859 if ((Flags & 7) != 4 /*MEM*/) {
3860 // Just skip over this operand, copying the operands verbatim.
3861 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
3862 i += (Flags >> 3) + 1;
3863 } else {
3864 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
3865 // Otherwise, this is a memory operand. Ask the target to select it.
3866 std::vector<SDOperand> SelOps;
3867 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
3868 std::cerr << "Could not match memory address. Inline asm failure!\n";
3869 exit(1);
3870 }
3871
3872 // Add this to the output node.
3873 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3874 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3875 i += 2;
3876 }
3877 }
3878
3879 // Add the flag input back if present.
3880 if (e != InOps.size())
3881 Ops.push_back(InOps.back());
3882}