blob: 17ee59762efa2e55fdbb7f07f1d39640efe9153c [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Jim Laskeydcb2b832006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000016#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000017#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000018#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000019#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000022#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskeya8bdac82006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000027#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000028#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman4ca2ea52006-04-22 18:53:45 +000031#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskey29e635d2006-08-02 12:30:23 +000033#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000034#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000036#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000037#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetFrameInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetMachine.h"
Vladimir Prusdf1d4392006-05-23 13:43:15 +000042#include "llvm/Target/TargetOptions.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner43535a12005-11-09 04:45:33 +000044#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000045#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000046#include "llvm/Support/Compiler.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000047#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000048#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000049#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000050#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000051using namespace llvm;
52
Chris Lattner975f5c92005-09-01 18:44:10 +000053#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000054static cl::opt<bool>
Evan Cheng739a6a42006-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 Lattnere05a4612005-01-12 03:41:21 +000060#else
Chris Lattneref598052006-04-02 03:07:27 +000061static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000062#endif
63
Jim Laskey29e635d2006-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 Chengc1e1d972006-01-23 07:01:07 +000077namespace {
Jim Laskey29e635d2006-08-02 12:30:23 +000078 cl::opt<RegisterScheduler::FunctionPassCtor, false,
79 RegisterPassParser<RegisterScheduler> >
Jim Laskey95eda5b2006-08-01 14:21:23 +000080 ISHeuristic("sched",
Chris Lattner524c1a22006-08-03 00:18:59 +000081 cl::init(&createDefaultScheduler),
Jim Laskey95eda5b2006-08-01 14:21:23 +000082 cl::desc("Instruction schedulers available:"));
83
Jim Laskey03593f72006-08-01 18:29:48 +000084 static RegisterScheduler
Jim Laskey17c67ef2006-08-01 19:14:14 +000085 defaultListDAGScheduler("default", " Best scheduler for the target",
86 createDefaultScheduler);
Evan Chengc1e1d972006-01-23 07:01:07 +000087} // namespace
88
Chris Lattner6f87d182006-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 Lattner996795b2006-06-28 23:17:24 +000094 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner6f87d182006-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 Lattnere7c0ffb2006-02-23 20:06:57 +0000123 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-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 Chengef9e07d2006-06-15 08:11:54 +0000129 SDOperand &Chain, SDOperand &Flag,
130 MVT::ValueType PtrVT) const;
Chris Lattner571d9642006-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 Lattnere7c0ffb2006-02-23 20:06:57 +0000136 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000137 };
138}
Evan Chengc1e1d972006-01-23 07:01:07 +0000139
Chris Lattner7a60d912005-01-07 07:47:53 +0000140namespace llvm {
141 //===--------------------------------------------------------------------===//
Jim Laskey17c67ef2006-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 Lattner7a60d912005-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 Lattnerd0061952005-01-08 19:52:31 +0000162 class FunctionLoweringInfo {
163 public:
Chris Lattner7a60d912005-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 Brukman835702a2005-04-21 22:36:52 +0000187
Chris Lattner49409cb2006-03-16 19:51:18 +0000188 unsigned CreateRegForValue(const Value *V);
189
Chris Lattner7a60d912005-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 Begemaned728c12006-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 Lattner7a60d912005-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 Begemaned728c12006-03-27 01:32:24 +0000205 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
206 isa<SwitchInst>(*UI))
Chris Lattner7a60d912005-01-07 07:47:53 +0000207 return true;
208 return false;
209}
210
Chris Lattner6871b232005-10-30 19:42:35 +0000211/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemaned728c12006-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 Lattner6871b232005-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 Begemaned728c12006-03-27 01:32:24 +0000217 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattner6871b232005-10-30 19:42:35 +0000218 return false; // Use not in entry block.
219 return true;
220}
221
Chris Lattner7a60d912005-01-07 07:47:53 +0000222FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000223 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000224 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
225
Chris Lattner6871b232005-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 Lattner7a60d912005-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 Cohenf8a5e5ae2005-10-01 03:57:14 +0000236 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-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 Spencere0fc4df2006-10-20 07:07:24 +0000239 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000240 const Type *Ty = AI->getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +0000241 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000242 unsigned Align =
Owen Anderson20a631f2006-05-03 01:29:57 +0000243 std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +0000244 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000245
Reid Spencere0fc4df2006-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 Lattnercbefe722005-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 Spencere0fc4df2006-10-20 07:07:24 +0000254 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000255 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000256 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000257 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000258 }
259
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000260 for (; BB != EB; ++BB)
261 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-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 Cohenf8a5e5ae2005-10-01 03:57:14 +0000270 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-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 Lattner8ea875f2005-01-07 21:34:19 +0000279 (PN = dyn_cast<PHINode>(I)); ++I)
280 if (!PN->use_empty()) {
Chris Lattner5fe1f542006-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 Lattner8ea875f2005-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 Lattner7a60d912005-01-07 07:47:53 +0000296 }
297}
298
Chris Lattner49409cb2006-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 Lattner7ececaa2006-03-16 23:05:19 +0000322 if (NumElts == 1)
323 VT = EltTy;
324 else
325 VT = getVectorType(EltTy, NumElts);
Chris Lattner49409cb2006-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 Lattner7a60d912005-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 Lattner4d9651c2005-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 Begemaned728c12006-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 Spencere0fc4df2006-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 Begemaned728c12006-03-27 01:32:24 +0000401
Reid Spencere0fc4df2006-10-20 07:07:24 +0000402 return cast<const ConstantInt>(C1.first)->getSExtValue() <
403 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemaned728c12006-03-27 01:32:24 +0000404 }
405 };
406
Chris Lattner7a60d912005-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 Anderson20a631f2006-05-03 01:29:57 +0000413 const TargetData *TD;
Chris Lattner7a60d912005-01-07 07:47:53 +0000414
Nate Begemaned728c12006-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 Begeman4ca2ea52006-04-22 18:53:45 +0000418 SelectionDAGISel::JumpTable JT;
Nate Begemaned728c12006-03-27 01:32:24 +0000419
Chris Lattner7a60d912005-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 Brukman835702a2005-04-21 22:36:52 +0000425 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000426 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman866b4b42006-04-23 06:26:20 +0000427 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000428 }
429
Chris Lattner4108bb02005-01-17 19:43:36 +0000430 /// getRoot - Return the current virtual root of the Selection DAG.
431 ///
432 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000433 if (PendingLoads.empty())
434 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000435
Chris Lattner4d9651c2005-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 Lattnerc24a1d32006-08-08 02:23:42 +0000444 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
445 &PendingLoads[0], PendingLoads.size());
Chris Lattner4d9651c2005-01-17 22:19:26 +0000446 PendingLoads.clear();
447 DAG.setRoot(Root);
448 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000449 }
450
Chris Lattner7a60d912005-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 Lattner4024c002006-03-15 22:19:46 +0000466 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000467 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +0000468 bool isVolatile);
Chris Lattner7a60d912005-01-07 07:47:53 +0000469
470 SDOperand getIntPtrConstant(uint64_t Val) {
471 return DAG.getConstant(Val, TLI.getPointerTy());
472 }
473
Chris Lattner8471b152006-03-16 19:57:50 +0000474 SDOperand getValue(const Value *V);
Chris Lattner7a60d912005-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 Lattner1558fc62006-02-01 18:59:47 +0000481
Chris Lattner6f87d182006-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 Begemaned728c12006-03-27 01:32:24 +0000487
Chris Lattner7a60d912005-01-07 07:47:53 +0000488 // Terminator instructions.
489 void visitRet(ReturnInst &I);
490 void visitBr(BranchInst &I);
Nate Begemaned728c12006-03-27 01:32:24 +0000491 void visitSwitch(SwitchInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000492 void visitUnreachable(UnreachableInst &I) { /* noop */ }
493
Nate Begemaned728c12006-03-27 01:32:24 +0000494 // Helper for visitSwitch
495 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000496 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemaned728c12006-03-27 01:32:24 +0000497
Chris Lattner7a60d912005-01-07 07:47:53 +0000498 // These all get lowered before this pass.
Chris Lattner7a60d912005-01-07 07:47:53 +0000499 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
500 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
501
Nate Begemanb2e089c2005-11-19 00:36:38 +0000502 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000503 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000504 void visitAdd(User &I) {
505 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000506 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000507 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000508 void visitMul(User &I) {
509 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000510 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000511 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000512 const Type *Ty = I.getType();
Evan Cheng3bf916d2006-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 Lattner7a60d912005-01-07 07:47:53 +0000516 }
517 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000518 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000519 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000520 }
Evan Cheng3bf916d2006-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 Begeman127321b2005-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 Lattner7a60d912005-01-07 07:47:53 +0000527 }
528
Evan Cheng1c5b7d12006-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 Lattner7a60d912005-01-07 07:47:53 +0000543
Chris Lattner67271862006-03-29 00:11:43 +0000544 void visitExtractElement(User &I);
545 void visitInsertElement(User &I);
Chris Lattner098c01e2006-04-08 04:15:24 +0000546 void visitShuffleVector(User &I);
Chris Lattner32206f52006-03-18 01:44:44 +0000547
Chris Lattner7a60d912005-01-07 07:47:53 +0000548 void visitGetElementPtr(User &I);
549 void visitCast(User &I);
550 void visitSelect(User &I);
Chris Lattner7a60d912005-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 Lattner476e67b2006-01-26 22:24:51 +0000559 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000560 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +0000561 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000562
Chris Lattner7a60d912005-01-07 07:47:53 +0000563 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000564 void visitVAArg(VAArgInst &I);
565 void visitVAEnd(CallInst &I);
566 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000567 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000568
Chris Lattner875def92005-01-11 05:56:49 +0000569 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-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 Lattner8471b152006-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 Lattnerc16b05e2006-03-19 00:20:20 +0000598 if (!isa<PackedType>(VTy))
599 return N = DAG.getNode(ISD::UNDEF, VT);
600
Chris Lattnerf4e1a532006-03-19 00:52:58 +0000601 // Create a VBUILD_VECTOR of undef nodes.
Chris Lattnerc16b05e2006-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 Lattnerc24a1d32006-08-08 02:23:42 +0000606 SmallVector<SDOperand, 8> Ops;
Chris Lattnerc16b05e2006-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 Lattnerc24a1d32006-08-08 02:23:42 +0000612 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
613 &Ops[0], Ops.size());
Chris Lattner8471b152006-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 Lattner8471b152006-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 Lattnerc24a1d32006-08-08 02:23:42 +0000623 SmallVector<SDOperand, 8> Ops;
Chris Lattner8471b152006-03-16 19:57:50 +0000624 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
Chris Lattner67271862006-03-29 00:11:43 +0000625 for (unsigned i = 0; i != NumElements; ++i)
626 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner8471b152006-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 Lattnerf4e1a532006-03-19 00:52:58 +0000637 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattnerc16b05e2006-03-19 00:20:20 +0000638 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
639 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000640 return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
Chris Lattner8471b152006-03-16 19:57:50 +0000641 } else {
642 // Canonicalize all constant ints to be unsigned.
Reid Spencere0fc4df2006-10-20 07:07:24 +0000643 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
Chris Lattner8471b152006-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 Lattner5fe1f542006-03-31 02:06:56 +0000661 if (VT != MVT::Vector) {
662 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
Chris Lattner8471b152006-03-16 19:57:50 +0000663
Chris Lattner5fe1f542006-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 Lattner8471b152006-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 Lattner5fe1f542006-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 Lattner4a2413a2006-04-05 06:54:42 +0000680 const PackedType *PTy = cast<PackedType>(VTy);
681 unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
Chris Lattner5fe1f542006-03-31 02:06:56 +0000682 PTyLegalElementVT);
683
684 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000685 SmallVector<SDOperand, 8> Ops;
Chris Lattner5fe1f542006-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 Lattnerc24a1d32006-08-08 02:23:42 +0000716 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner4a2413a2006-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 Lattner8471b152006-03-16 19:57:50 +0000724 }
725
726 return N;
727}
728
729
Chris Lattner7a60d912005-01-07 07:47:53 +0000730void SelectionDAGLowering::visitRet(ReturnInst &I) {
731 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000732 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000733 return;
734 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000735 SmallVector<SDOperand, 8> NewValues;
Nate Begeman8c47c3a2006-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 Chenga2e99532006-05-26 23:09:09 +0000739 bool isSigned = I.getOperand(i)->getType()->isSigned();
Nate Begeman8c47c3a2006-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 Chenga2e99532006-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 Begeman8c47c3a2006-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 Lattner7a60d912005-01-07 07:47:53 +0000753
Evan Chenga2e99532006-05-26 23:09:09 +0000754 if (isSigned)
Nate Begeman8c47c3a2006-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 Chenga2e99532006-05-26 23:09:09 +0000760 NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner7a60d912005-01-07 07:47:53 +0000761 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +0000762 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
763 &NewValues[0], NewValues.size()));
Chris Lattner7a60d912005-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)];
Nate Begemaned728c12006-03-27 01:32:24 +0000769 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000770
771 // Figure out which block is immediately after the current one.
772 MachineBasicBlock *NextBlock = 0;
773 MachineFunction::iterator BBI = CurMBB;
774 if (++BBI != CurMBB->getParent()->end())
775 NextBlock = BBI;
776
777 if (I.isUnconditional()) {
778 // If this is not a fall-through branch, emit the branch.
779 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000780 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000781 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000782 } else {
783 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Nate Begemaned728c12006-03-27 01:32:24 +0000784 CurMBB->addSuccessor(Succ1MBB);
Chris Lattner7a60d912005-01-07 07:47:53 +0000785
786 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000787 if (Succ1MBB == NextBlock) {
788 // If the condition is false, fall through. This means we should branch
789 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000790 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000791 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000792 } else if (Succ0MBB == NextBlock) {
793 // If the condition is true, fall through. This means we should branch if
794 // the condition is false to Succ #1. Invert the condition first.
795 SDOperand True = DAG.getConstant(1, Cond.getValueType());
796 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000797 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000798 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000799 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000800 std::vector<SDOperand> Ops;
801 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000802 // If the false case is the current basic block, then this is a self
803 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
804 // adds an extra instruction in the loop. Instead, invert the
805 // condition and emit "Loop: ... br!cond Loop; br Out.
806 if (CurMBB == Succ1MBB) {
807 std::swap(Succ0MBB, Succ1MBB);
808 SDOperand True = DAG.getConstant(1, Cond.getValueType());
809 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
810 }
Nate Begemanbb01d4f2006-03-17 01:40:33 +0000811 SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
812 DAG.getBasicBlock(Succ0MBB));
813 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
814 DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000815 }
816 }
817}
818
Nate Begemaned728c12006-03-27 01:32:24 +0000819/// visitSwitchCase - Emits the necessary code to represent a single node in
820/// the binary search tree resulting from lowering a switch instruction.
821void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner3f179d22006-10-24 17:03:35 +0000822 SDOperand Cond = DAG.getSetCC(MVT::i1, getValue(CB.CmpLHS),
823 getValue(CB.CmpRHS), CB.CC);
Nate Begemaned728c12006-03-27 01:32:24 +0000824
825 // Set NextBlock to be the MBB immediately after the current one, if any.
826 // This is used to avoid emitting unnecessary branches to the next block.
827 MachineBasicBlock *NextBlock = 0;
828 MachineFunction::iterator BBI = CurMBB;
829 if (++BBI != CurMBB->getParent()->end())
830 NextBlock = BBI;
831
832 // If the lhs block is the next block, invert the condition so that we can
833 // fall through to the lhs instead of the rhs block.
834 if (CB.LHSBB == NextBlock) {
835 std::swap(CB.LHSBB, CB.RHSBB);
836 SDOperand True = DAG.getConstant(1, Cond.getValueType());
837 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
838 }
839 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
840 DAG.getBasicBlock(CB.LHSBB));
841 if (CB.RHSBB == NextBlock)
842 DAG.setRoot(BrCond);
843 else
844 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
845 DAG.getBasicBlock(CB.RHSBB)));
846 // Update successor info
847 CurMBB->addSuccessor(CB.LHSBB);
848 CurMBB->addSuccessor(CB.RHSBB);
849}
850
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000851void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000852 // Emit the code for the jump table
853 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000854 assert((PTy == MVT::i32 || PTy == MVT::i64) &&
855 "Jump table entries are 32-bit values");
Evan Cheng77c07572006-09-24 05:22:38 +0000856 bool isPIC = TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_;
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000857 // PIC jump table entries are 32-bit values.
Evan Cheng77c07572006-09-24 05:22:38 +0000858 unsigned EntrySize = isPIC ? 4 : MVT::getSizeInBits(PTy)/8;
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000859 SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
860 SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
Evan Cheng6ae6ac12006-08-01 01:03:13 +0000861 DAG.getConstant(EntrySize, PTy));
Nate Begeman78756502006-07-27 01:13:04 +0000862 SDOperand TAB = DAG.getJumpTable(JT.JTI,PTy);
863 SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, TAB);
Evan Cheng77c07572006-09-24 05:22:38 +0000864 SDOperand LD = DAG.getLoad(isPIC ? MVT::i32 : PTy, Copy.getValue(1), ADD,
Evan Chenge71fe34d2006-10-09 20:57:25 +0000865 NULL, 0);
Evan Cheng77c07572006-09-24 05:22:38 +0000866 if (isPIC) {
Andrew Lenharthc19ef922006-09-26 20:02:30 +0000867 // For Pic, the sequence is:
868 // BRIND(load(Jumptable + index) + RelocBase)
869 // RelocBase is the JumpTable on PPC and X86, GOT on Alpha
Andrew Lenhartha6bbf332006-10-11 04:29:42 +0000870 SDOperand Reloc;
871 if (TLI.usesGlobalOffsetTable())
872 Reloc = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, PTy);
873 else
874 Reloc = TAB;
Chris Lattner4c3ef472006-10-22 22:47:10 +0000875 ADD = (PTy != MVT::i32) ? DAG.getNode(ISD::SIGN_EXTEND, PTy, LD) : LD;
876 ADD = DAG.getNode(ISD::ADD, PTy, ADD, Reloc);
Nate Begeman78756502006-07-27 01:13:04 +0000877 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), ADD));
878 } else {
879 DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
880 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000881}
882
Nate Begemaned728c12006-03-27 01:32:24 +0000883void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
884 // Figure out which block is immediately after the current one.
885 MachineBasicBlock *NextBlock = 0;
886 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000887
Nate Begemaned728c12006-03-27 01:32:24 +0000888 if (++BBI != CurMBB->getParent()->end())
889 NextBlock = BBI;
890
Chris Lattner6d6fc262006-10-22 21:36:53 +0000891 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
892
Nate Begemaned728c12006-03-27 01:32:24 +0000893 // If there is only the default destination, branch to it if it is not the
894 // next basic block. Otherwise, just fall through.
895 if (I.getNumOperands() == 2) {
896 // Update machine-CFG edges.
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000897
Nate Begemaned728c12006-03-27 01:32:24 +0000898 // If this is not a fall-through branch, emit the branch.
Chris Lattner6d6fc262006-10-22 21:36:53 +0000899 if (Default != NextBlock)
Nate Begemaned728c12006-03-27 01:32:24 +0000900 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattner6d6fc262006-10-22 21:36:53 +0000901 DAG.getBasicBlock(Default)));
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000902
Chris Lattner6d6fc262006-10-22 21:36:53 +0000903 CurMBB->addSuccessor(Default);
Nate Begemaned728c12006-03-27 01:32:24 +0000904 return;
905 }
906
907 // If there are any non-default case statements, create a vector of Cases
908 // representing each one, and sort the vector so that we can efficiently
909 // create a binary search tree from them.
910 std::vector<Case> Cases;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000911
Nate Begemaned728c12006-03-27 01:32:24 +0000912 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
913 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
914 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
915 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +0000916
Nate Begemaned728c12006-03-27 01:32:24 +0000917 std::sort(Cases.begin(), Cases.end(), CaseCmp());
918
919 // Get the Value to be switched on and default basic blocks, which will be
920 // inserted into CaseBlock records, representing basic blocks in the binary
921 // search tree.
922 Value *SV = I.getOperand(0);
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000923
924 // Get the MachineFunction which holds the current MBB. This is used during
925 // emission of jump tables, and when inserting any additional MBBs necessary
926 // to represent the switch.
Nate Begemaned728c12006-03-27 01:32:24 +0000927 MachineFunction *CurMF = CurMBB->getParent();
928 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattner6d6fc262006-10-22 21:36:53 +0000929
930 // If the switch has few cases (two or less) emit a series of specific
931 // tests.
Chris Lattner76a7bc82006-10-22 23:00:53 +0000932 if (Cases.size() < 3) {
Chris Lattner6d6fc262006-10-22 21:36:53 +0000933 // TODO: If any two of the cases has the same destination, and if one value
934 // is the same as the other, but has one bit unset that the other has set,
935 // use bit manipulation to do two compares at once. For example:
936 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
937
Chris Lattner4c931502006-10-23 18:38:22 +0000938 // Rearrange the case blocks so that the last one falls through if possible.
939 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
940 // The last case block won't fall through into 'NextBlock' if we emit the
941 // branches in this order. See if rearranging a case value would help.
942 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
943 if (Cases[i].second == NextBlock) {
944 std::swap(Cases[i], Cases.back());
945 break;
946 }
947 }
948 }
949
950
Chris Lattner6d6fc262006-10-22 21:36:53 +0000951 // Create a CaseBlock record representing a conditional branch to
952 // the Case's target mbb if the value being switched on SV is equal
953 // to C.
954 MachineBasicBlock *CurBlock = CurMBB;
955 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
956 MachineBasicBlock *FallThrough;
957 if (i != e-1) {
958 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
959 CurMF->getBasicBlockList().insert(BBI, FallThrough);
960 } else {
961 // If the last case doesn't match, go to the default block.
962 FallThrough = Default;
963 }
964
965 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
966 Cases[i].second, FallThrough, CurBlock);
967
968 // If emitting the first comparison, just call visitSwitchCase to emit the
969 // code into the current block. Otherwise, push the CaseBlock onto the
970 // vector to be later processed by SDISel, and insert the node's MBB
971 // before the next MBB.
972 if (CurBlock == CurMBB)
973 visitSwitchCase(CB);
974 else
975 SwitchCases.push_back(CB);
976
977 CurBlock = FallThrough;
978 }
979 return;
980 }
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000981
Nate Begemand7a19102006-05-08 16:51:36 +0000982 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
983 // target supports indirect branches, then emit a jump table rather than
984 // lowering the switch to a binary tree of conditional branches.
Nate Begeman866b4b42006-04-23 06:26:20 +0000985 if (TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
Nate Begemandf488392006-05-03 03:48:02 +0000986 Cases.size() > 5) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000987 uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
988 uint64_t Last = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
Nate Begemandf488392006-05-03 03:48:02 +0000989 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
990
Nate Begemand7a19102006-05-08 16:51:36 +0000991 if (Density >= 0.3125) {
Nate Begeman4ca2ea52006-04-22 18:53:45 +0000992 // Create a new basic block to hold the code for loading the address
993 // of the jump table, and jumping to it. Update successor information;
994 // we will either branch to the default case for the switch, or the jump
995 // table.
996 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
997 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
998 CurMBB->addSuccessor(Default);
999 CurMBB->addSuccessor(JumpTableBB);
1000
1001 // Subtract the lowest switch case value from the value being switched on
1002 // and conditional branch to default mbb if the result is greater than the
1003 // difference between smallest and largest cases.
1004 SDOperand SwitchOp = getValue(SV);
1005 MVT::ValueType VT = SwitchOp.getValueType();
1006 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1007 DAG.getConstant(First, VT));
1008
1009 // The SDNode we just created, which holds the value being switched on
1010 // minus the the smallest case value, needs to be copied to a virtual
1011 // register so it can be used as an index into the jump table in a
1012 // subsequent basic block. This value may be smaller or larger than the
1013 // target's pointer type, and therefore require extension or truncating.
1014 if (VT > TLI.getPointerTy())
1015 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1016 else
1017 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001018
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001019 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1020 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1021
1022 // Emit the range check for the jump table, and branch to the default
1023 // block for the switch statement if the value being switched on exceeds
1024 // the largest case in the switch.
1025 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1026 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1027 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1028 DAG.getBasicBlock(Default)));
1029
Nate Begemandf488392006-05-03 03:48:02 +00001030 // Build a vector of destination BBs, corresponding to each target
1031 // of the jump table. If the value of the jump table slot corresponds to
1032 // a case statement, push the case's BB onto the vector, otherwise, push
1033 // the default BB.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001034 std::vector<MachineBasicBlock*> DestBBs;
Nate Begemandf488392006-05-03 03:48:02 +00001035 uint64_t TEI = First;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001036 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Reid Spencere0fc4df2006-10-20 07:07:24 +00001037 if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
Nate Begemandf488392006-05-03 03:48:02 +00001038 DestBBs.push_back(ii->second);
Nate Begemandf488392006-05-03 03:48:02 +00001039 ++ii;
1040 } else {
1041 DestBBs.push_back(Default);
Nate Begemandf488392006-05-03 03:48:02 +00001042 }
Nate Begemandf488392006-05-03 03:48:02 +00001043
1044 // Update successor info
Chris Lattner2e0dfb02006-09-10 06:36:57 +00001045 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1046 E = DestBBs.end(); I != E; ++I)
1047 JumpTableBB->addSuccessor(*I);
Nate Begemandf488392006-05-03 03:48:02 +00001048
1049 // Create a jump table index for this jump table, or return an existing
1050 // one.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001051 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1052
1053 // Set the jump table information so that we can codegen it as a second
1054 // MachineBasicBlock
1055 JT.Reg = JumpTableReg;
1056 JT.JTI = JTI;
1057 JT.MBB = JumpTableBB;
Nate Begeman866b4b42006-04-23 06:26:20 +00001058 JT.Default = Default;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00001059 return;
1060 }
1061 }
Nate Begemaned728c12006-03-27 01:32:24 +00001062
1063 // Push the initial CaseRec onto the worklist
1064 std::vector<CaseRec> CaseVec;
1065 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1066
1067 while (!CaseVec.empty()) {
1068 // Grab a record representing a case range to process off the worklist
1069 CaseRec CR = CaseVec.back();
1070 CaseVec.pop_back();
1071
1072 // Size is the number of Cases represented by this range. If Size is 1,
1073 // then we are processing a leaf of the binary search tree. Otherwise,
1074 // we need to pick a pivot, and push left and right ranges onto the
1075 // worklist.
1076 unsigned Size = CR.Range.second - CR.Range.first;
1077
1078 if (Size == 1) {
1079 // Create a CaseBlock record representing a conditional branch to
1080 // the Case's target mbb if the value being switched on SV is equal
1081 // to C. Otherwise, branch to default.
1082 Constant *C = CR.Range.first->first;
1083 MachineBasicBlock *Target = CR.Range.first->second;
1084 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1085 CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001086
Nate Begemaned728c12006-03-27 01:32:24 +00001087 // If the MBB representing the leaf node is the current MBB, then just
1088 // call visitSwitchCase to emit the code into the current block.
1089 // Otherwise, push the CaseBlock onto the vector to be later processed
1090 // by SDISel, and insert the node's MBB before the next MBB.
1091 if (CR.CaseBB == CurMBB)
1092 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001093 else
Nate Begemaned728c12006-03-27 01:32:24 +00001094 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001095 } else {
1096 // split case range at pivot
1097 CaseItr Pivot = CR.Range.first + (Size / 2);
1098 CaseRange LHSR(CR.Range.first, Pivot);
1099 CaseRange RHSR(Pivot, CR.Range.second);
1100 Constant *C = Pivot->first;
1101 MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001102
Nate Begemaned728c12006-03-27 01:32:24 +00001103 // We know that we branch to the LHS if the Value being switched on is
1104 // less than the Pivot value, C. We use this to optimize our binary
1105 // tree a bit, by recognizing that if SV is greater than or equal to the
1106 // LHS's Case Value, and that Case Value is exactly one less than the
1107 // Pivot's Value, then we can branch directly to the LHS's Target,
1108 // rather than creating a leaf node for it.
1109 if ((LHSR.second - LHSR.first) == 1 &&
1110 LHSR.first->first == CR.GE &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001111 cast<ConstantIntegral>(C)->getZExtValue() ==
1112 (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
Nate Begemaned728c12006-03-27 01:32:24 +00001113 LHSBB = LHSR.first->second;
1114 } else {
1115 LHSBB = new MachineBasicBlock(LLVMBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001116 CurMF->getBasicBlockList().insert(BBI, LHSBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001117 CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
1118 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001119
Nate Begemaned728c12006-03-27 01:32:24 +00001120 // Similar to the optimization above, if the Value being switched on is
1121 // known to be less than the Constant CR.LT, and the current Case Value
1122 // is CR.LT - 1, then we can branch directly to the target block for
1123 // the current Case Value, rather than emitting a RHS leaf node for it.
1124 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Reid Spencere0fc4df2006-10-20 07:07:24 +00001125 cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1126 (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
Nate Begemaned728c12006-03-27 01:32:24 +00001127 RHSBB = RHSR.first->second;
1128 } else {
1129 RHSBB = new MachineBasicBlock(LLVMBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001130 CurMF->getBasicBlockList().insert(BBI, RHSBB);
Nate Begemaned728c12006-03-27 01:32:24 +00001131 CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
1132 }
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001133
Nate Begemaned728c12006-03-27 01:32:24 +00001134 // Create a CaseBlock record representing a conditional branch to
1135 // the LHS node if the value being switched on SV is less than C.
1136 // Otherwise, branch to LHS.
1137 ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
1138 SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001139
Nate Begemaned728c12006-03-27 01:32:24 +00001140 if (CR.CaseBB == CurMBB)
1141 visitSwitchCase(CB);
Bill Wendlingbe96e1c2006-10-19 21:46:38 +00001142 else
Nate Begemaned728c12006-03-27 01:32:24 +00001143 SwitchCases.push_back(CB);
Nate Begemaned728c12006-03-27 01:32:24 +00001144 }
1145 }
1146}
1147
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001148void SelectionDAGLowering::visitSub(User &I) {
1149 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +00001150 if (I.getType()->isFloatingPoint()) {
1151 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1152 if (CFP->isExactlyValue(-0.0)) {
1153 SDOperand Op2 = getValue(I.getOperand(1));
1154 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1155 return;
1156 }
Chris Lattner6f3b5772005-09-28 22:28:18 +00001157 }
Nate Begemanb2e089c2005-11-19 00:36:38 +00001158 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +00001159}
1160
Nate Begemanb2e089c2005-11-19 00:36:38 +00001161void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
1162 unsigned VecOp) {
1163 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001164 SDOperand Op1 = getValue(I.getOperand(0));
1165 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +00001166
Chris Lattner19baba62005-11-19 18:40:42 +00001167 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001168 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1169 } else if (Ty->isFloatingPoint()) {
1170 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1171 } else {
1172 const PackedType *PTy = cast<PackedType>(Ty);
Chris Lattner32206f52006-03-18 01:44:44 +00001173 SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1174 SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1175 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001176 }
Nate Begeman127321b2005-11-18 07:42:56 +00001177}
Chris Lattner96c26752005-01-19 22:31:21 +00001178
Nate Begeman127321b2005-11-18 07:42:56 +00001179void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1180 SDOperand Op1 = getValue(I.getOperand(0));
1181 SDOperand Op2 = getValue(I.getOperand(1));
1182
1183 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1184
Chris Lattner7a60d912005-01-07 07:47:53 +00001185 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1186}
1187
1188void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001189 ISD::CondCode UnsignedOpcode,
1190 ISD::CondCode FPOpcode) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001191 SDOperand Op1 = getValue(I.getOperand(0));
1192 SDOperand Op2 = getValue(I.getOperand(1));
1193 ISD::CondCode Opcode = SignedOpcode;
Evan Chengac4f66f2006-05-23 18:18:46 +00001194 if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
Evan Cheng1c5b7d12006-05-23 06:40:47 +00001195 Opcode = FPOpcode;
1196 else if (I.getOperand(0)->getType()->isUnsigned())
Chris Lattner7a60d912005-01-07 07:47:53 +00001197 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +00001198 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +00001199}
1200
1201void SelectionDAGLowering::visitSelect(User &I) {
1202 SDOperand Cond = getValue(I.getOperand(0));
1203 SDOperand TrueVal = getValue(I.getOperand(1));
1204 SDOperand FalseVal = getValue(I.getOperand(2));
Chris Lattner02274a52006-04-08 22:22:57 +00001205 if (!isa<PackedType>(I.getType())) {
1206 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1207 TrueVal, FalseVal));
1208 } else {
1209 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1210 *(TrueVal.Val->op_end()-2),
1211 *(TrueVal.Val->op_end()-1)));
1212 }
Chris Lattner7a60d912005-01-07 07:47:53 +00001213}
1214
1215void SelectionDAGLowering::visitCast(User &I) {
1216 SDOperand N = getValue(I.getOperand(0));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001217 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner4024c002006-03-15 22:19:46 +00001218 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner7a60d912005-01-07 07:47:53 +00001219
Chris Lattner2f4119a2006-03-22 20:09:35 +00001220 if (DestVT == MVT::Vector) {
1221 // This is a cast to a vector from something else. This is always a bit
1222 // convert. Get information about the input vector.
1223 const PackedType *DestTy = cast<PackedType>(I.getType());
1224 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1225 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1226 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1227 DAG.getValueType(EltVT)));
1228 } else if (SrcVT == DestVT) {
Chris Lattner7a60d912005-01-07 07:47:53 +00001229 setValue(&I, N); // noop cast.
Chris Lattner4024c002006-03-15 22:19:46 +00001230 } else if (DestVT == MVT::i1) {
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001231 // Cast to bool is a comparison against zero, not truncation to zero.
Chris Lattner4024c002006-03-15 22:19:46 +00001232 SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
Chris Lattner2d8b55c2005-05-09 22:17:13 +00001233 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +00001234 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner4024c002006-03-15 22:19:46 +00001235 } else if (isInteger(SrcVT)) {
1236 if (isInteger(DestVT)) { // Int -> Int cast
1237 if (DestVT < SrcVT) // Truncating cast?
1238 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001239 else if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001240 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001241 else
Chris Lattner4024c002006-03-15 22:19:46 +00001242 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
Chris Lattnerb893d042006-03-22 22:20:49 +00001243 } else if (isFloatingPoint(DestVT)) { // Int -> FP cast
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001244 if (I.getOperand(0)->getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001245 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001246 else
Chris Lattner4024c002006-03-15 22:19:46 +00001247 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001248 } else {
1249 assert(0 && "Unknown cast!");
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001250 }
Chris Lattner4024c002006-03-15 22:19:46 +00001251 } else if (isFloatingPoint(SrcVT)) {
1252 if (isFloatingPoint(DestVT)) { // FP -> FP cast
1253 if (DestVT < SrcVT) // Rounding cast?
1254 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001255 else
Chris Lattner4024c002006-03-15 22:19:46 +00001256 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001257 } else if (isInteger(DestVT)) { // FP -> Int cast.
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001258 if (I.getType()->isSigned())
Chris Lattner4024c002006-03-15 22:19:46 +00001259 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
Chris Lattner2a6db3c2005-01-08 08:08:56 +00001260 else
Chris Lattner4024c002006-03-15 22:19:46 +00001261 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
Chris Lattner2f4119a2006-03-22 20:09:35 +00001262 } else {
1263 assert(0 && "Unknown cast!");
Chris Lattner4024c002006-03-15 22:19:46 +00001264 }
1265 } else {
Chris Lattner2f4119a2006-03-22 20:09:35 +00001266 assert(SrcVT == MVT::Vector && "Unknown cast!");
1267 assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1268 // This is a cast from a vector to something else. This is always a bit
1269 // convert. Get information about the input vector.
1270 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Chris Lattner7a60d912005-01-07 07:47:53 +00001271 }
1272}
1273
Chris Lattner67271862006-03-29 00:11:43 +00001274void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattner32206f52006-03-18 01:44:44 +00001275 SDOperand InVec = getValue(I.getOperand(0));
1276 SDOperand InVal = getValue(I.getOperand(1));
1277 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1278 getValue(I.getOperand(2)));
1279
Chris Lattner29b23012006-03-19 01:17:20 +00001280 SDOperand Num = *(InVec.Val->op_end()-2);
1281 SDOperand Typ = *(InVec.Val->op_end()-1);
1282 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1283 InVec, InVal, InIdx, Num, Typ));
Chris Lattner32206f52006-03-18 01:44:44 +00001284}
1285
Chris Lattner67271862006-03-29 00:11:43 +00001286void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner7c0cd8c2006-03-21 20:44:12 +00001287 SDOperand InVec = getValue(I.getOperand(0));
1288 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1289 getValue(I.getOperand(1)));
1290 SDOperand Typ = *(InVec.Val->op_end()-1);
1291 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1292 TLI.getValueType(I.getType()), InVec, InIdx));
1293}
Chris Lattner32206f52006-03-18 01:44:44 +00001294
Chris Lattner098c01e2006-04-08 04:15:24 +00001295void SelectionDAGLowering::visitShuffleVector(User &I) {
1296 SDOperand V1 = getValue(I.getOperand(0));
1297 SDOperand V2 = getValue(I.getOperand(1));
1298 SDOperand Mask = getValue(I.getOperand(2));
1299
1300 SDOperand Num = *(V1.Val->op_end()-2);
1301 SDOperand Typ = *(V2.Val->op_end()-1);
1302 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1303 V1, V2, Mask, Num, Typ));
1304}
1305
1306
Chris Lattner7a60d912005-01-07 07:47:53 +00001307void SelectionDAGLowering::visitGetElementPtr(User &I) {
1308 SDOperand N = getValue(I.getOperand(0));
1309 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner7a60d912005-01-07 07:47:53 +00001310
1311 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1312 OI != E; ++OI) {
1313 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +00001314 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001315 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner7a60d912005-01-07 07:47:53 +00001316 if (Field) {
1317 // N = N + Offset
Owen Anderson20a631f2006-05-03 01:29:57 +00001318 uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner7a60d912005-01-07 07:47:53 +00001319 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +00001320 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +00001321 }
1322 Ty = StTy->getElementType(Field);
1323 } else {
1324 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +00001325
Chris Lattner43535a12005-11-09 04:45:33 +00001326 // If this is a constant subscript, handle it quickly.
1327 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001328 if (CI->getZExtValue() == 0) continue;
Chris Lattner43535a12005-11-09 04:45:33 +00001329 uint64_t Offs;
Reid Spencere0fc4df2006-10-20 07:07:24 +00001330 if (CI->getType()->isSigned())
1331 Offs = (int64_t)
1332 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001333 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00001334 Offs =
1335 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
Chris Lattner43535a12005-11-09 04:45:33 +00001336 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1337 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +00001338 }
Chris Lattner43535a12005-11-09 04:45:33 +00001339
1340 // N = N + Idx * ElementSize;
Owen Anderson20a631f2006-05-03 01:29:57 +00001341 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner43535a12005-11-09 04:45:33 +00001342 SDOperand IdxN = getValue(Idx);
1343
1344 // If the index is smaller or larger than intptr_t, truncate or extend
1345 // it.
1346 if (IdxN.getValueType() < N.getValueType()) {
1347 if (Idx->getType()->isSigned())
1348 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1349 else
1350 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1351 } else if (IdxN.getValueType() > N.getValueType())
1352 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1353
1354 // If this is a multiply by a power of two, turn it into a shl
1355 // immediately. This is a very common case.
1356 if (isPowerOf2_64(ElementSize)) {
1357 unsigned Amt = Log2_64(ElementSize);
1358 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +00001359 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +00001360 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1361 continue;
1362 }
1363
1364 SDOperand Scale = getIntPtrConstant(ElementSize);
1365 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1366 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +00001367 }
1368 }
1369 setValue(&I, N);
1370}
1371
1372void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1373 // If this is a fixed sized alloca in the entry block of the function,
1374 // allocate it statically on the stack.
1375 if (FuncInfo.StaticAllocaMap.count(&I))
1376 return; // getValue will auto-populate this.
1377
1378 const Type *Ty = I.getAllocatedType();
Owen Anderson20a631f2006-05-03 01:29:57 +00001379 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1380 unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
Nate Begeman3ee3e692005-11-06 09:00:38 +00001381 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +00001382
1383 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +00001384 MVT::ValueType IntPtr = TLI.getPointerTy();
1385 if (IntPtr < AllocSize.getValueType())
1386 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1387 else if (IntPtr > AllocSize.getValueType())
1388 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +00001389
Chris Lattnereccb73d2005-01-22 23:04:37 +00001390 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +00001391 getIntPtrConstant(TySize));
1392
1393 // Handle alignment. If the requested alignment is less than or equal to the
1394 // stack alignment, ignore it and round the size of the allocation up to the
1395 // stack alignment size. If the size is greater than the stack alignment, we
1396 // note this in the DYNAMIC_STACKALLOC node.
1397 unsigned StackAlign =
1398 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1399 if (Align <= StackAlign) {
1400 Align = 0;
1401 // Add SA-1 to the size.
1402 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1403 getIntPtrConstant(StackAlign-1));
1404 // Mask out the low bits for alignment purposes.
1405 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1406 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1407 }
1408
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001409 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerbd887772006-08-14 23:53:35 +00001410 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1411 MVT::Other);
1412 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner7a60d912005-01-07 07:47:53 +00001413 DAG.setRoot(setValue(&I, DSA).getValue(1));
1414
1415 // Inform the Frame Information that we have just allocated a variable-sized
1416 // object.
1417 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1418}
1419
Chris Lattner7a60d912005-01-07 07:47:53 +00001420void SelectionDAGLowering::visitLoad(LoadInst &I) {
1421 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +00001422
Chris Lattner4d9651c2005-01-17 22:19:26 +00001423 SDOperand Root;
1424 if (I.isVolatile())
1425 Root = getRoot();
1426 else {
1427 // Do not serialize non-volatile loads against each other.
1428 Root = DAG.getRoot();
1429 }
Chris Lattner4024c002006-03-15 22:19:46 +00001430
Evan Chenge71fe34d2006-10-09 20:57:25 +00001431 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner4024c002006-03-15 22:19:46 +00001432 Root, I.isVolatile()));
1433}
1434
1435SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Chenge71fe34d2006-10-09 20:57:25 +00001436 const Value *SV, SDOperand Root,
Chris Lattner4024c002006-03-15 22:19:46 +00001437 bool isVolatile) {
Nate Begemanb2e089c2005-11-19 00:36:38 +00001438 SDOperand L;
Nate Begeman41b1cdc2005-12-06 06:18:55 +00001439 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +00001440 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Chenge71fe34d2006-10-09 20:57:25 +00001441 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1442 DAG.getSrcValue(SV));
Nate Begemanb2e089c2005-11-19 00:36:38 +00001443 } else {
Evan Chenge71fe34d2006-10-09 20:57:25 +00001444 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
Nate Begemanb2e089c2005-11-19 00:36:38 +00001445 }
Chris Lattner4d9651c2005-01-17 22:19:26 +00001446
Chris Lattner4024c002006-03-15 22:19:46 +00001447 if (isVolatile)
Chris Lattner4d9651c2005-01-17 22:19:26 +00001448 DAG.setRoot(L.getValue(1));
1449 else
1450 PendingLoads.push_back(L.getValue(1));
Chris Lattner4024c002006-03-15 22:19:46 +00001451
1452 return L;
Chris Lattner7a60d912005-01-07 07:47:53 +00001453}
1454
1455
1456void SelectionDAGLowering::visitStore(StoreInst &I) {
1457 Value *SrcV = I.getOperand(0);
1458 SDOperand Src = getValue(SrcV);
1459 SDOperand Ptr = getValue(I.getOperand(1));
Evan Chengab51cf22006-10-13 21:14:26 +00001460 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1461 I.isVolatile()));
Chris Lattner7a60d912005-01-07 07:47:53 +00001462}
1463
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001464/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1465/// access memory and has no other side effects at all.
1466static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1467#define GET_NO_MEMORY_INTRINSICS
1468#include "llvm/Intrinsics.gen"
1469#undef GET_NO_MEMORY_INTRINSICS
1470 return false;
1471}
1472
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001473// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1474// have any side-effects or if it only reads memory.
1475static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1476#define GET_SIDE_EFFECT_INFO
1477#include "llvm/Intrinsics.gen"
1478#undef GET_SIDE_EFFECT_INFO
1479 return false;
1480}
1481
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001482/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1483/// node.
1484void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1485 unsigned Intrinsic) {
Chris Lattner313229c2006-03-24 22:49:42 +00001486 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001487 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001488
1489 // Build the operand list.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001490 SmallVector<SDOperand, 8> Ops;
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001491 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1492 if (OnlyLoad) {
1493 // We don't need to serialize loads against other loads.
1494 Ops.push_back(DAG.getRoot());
1495 } else {
1496 Ops.push_back(getRoot());
1497 }
1498 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001499
1500 // Add the intrinsic ID as an integer operand.
1501 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1502
1503 // Add all operands of the call to the operand list.
1504 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1505 SDOperand Op = getValue(I.getOperand(i));
1506
1507 // If this is a vector type, force it to the right packed type.
1508 if (Op.getValueType() == MVT::Vector) {
1509 const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1510 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1511
1512 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1513 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1514 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1515 }
1516
1517 assert(TLI.isTypeLegal(Op.getValueType()) &&
1518 "Intrinsic uses a non-legal type?");
1519 Ops.push_back(Op);
1520 }
1521
1522 std::vector<MVT::ValueType> VTs;
1523 if (I.getType() != Type::VoidTy) {
1524 MVT::ValueType VT = TLI.getValueType(I.getType());
1525 if (VT == MVT::Vector) {
1526 const PackedType *DestTy = cast<PackedType>(I.getType());
1527 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1528
1529 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1530 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1531 }
1532
1533 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1534 VTs.push_back(VT);
1535 }
1536 if (HasChain)
1537 VTs.push_back(MVT::Other);
1538
Chris Lattnerbd887772006-08-14 23:53:35 +00001539 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1540
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001541 // Create the node.
Chris Lattnere55d1712006-03-28 00:40:33 +00001542 SDOperand Result;
1543 if (!HasChain)
Chris Lattnerbd887772006-08-14 23:53:35 +00001544 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1545 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001546 else if (I.getType() != Type::VoidTy)
Chris Lattnerbd887772006-08-14 23:53:35 +00001547 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1548 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001549 else
Chris Lattnerbd887772006-08-14 23:53:35 +00001550 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1551 &Ops[0], Ops.size());
Chris Lattnere55d1712006-03-28 00:40:33 +00001552
Chris Lattnera9c59156b2006-04-02 03:41:14 +00001553 if (HasChain) {
1554 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1555 if (OnlyLoad)
1556 PendingLoads.push_back(Chain);
1557 else
1558 DAG.setRoot(Chain);
1559 }
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001560 if (I.getType() != Type::VoidTy) {
1561 if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1562 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1563 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1564 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1565 DAG.getValueType(EVT));
1566 }
1567 setValue(&I, Result);
1568 }
1569}
1570
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001571/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1572/// we want to emit this as a call to a named external function, return the name
1573/// otherwise lower it and return null.
1574const char *
1575SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1576 switch (Intrinsic) {
Chris Lattnerd96b09a2006-03-24 02:22:33 +00001577 default:
1578 // By default, turn this into a target intrinsic node.
1579 visitTargetIntrinsic(I, Intrinsic);
1580 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001581 case Intrinsic::vastart: visitVAStart(I); return 0;
1582 case Intrinsic::vaend: visitVAEnd(I); return 0;
1583 case Intrinsic::vacopy: visitVACopy(I); return 0;
1584 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1585 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
1586 case Intrinsic::setjmp:
1587 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1588 break;
1589 case Intrinsic::longjmp:
1590 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1591 break;
Chris Lattner093c1592006-03-03 00:00:25 +00001592 case Intrinsic::memcpy_i32:
1593 case Intrinsic::memcpy_i64:
1594 visitMemIntrinsic(I, ISD::MEMCPY);
1595 return 0;
1596 case Intrinsic::memset_i32:
1597 case Intrinsic::memset_i64:
1598 visitMemIntrinsic(I, ISD::MEMSET);
1599 return 0;
1600 case Intrinsic::memmove_i32:
1601 case Intrinsic::memmove_i64:
1602 visitMemIntrinsic(I, ISD::MEMMOVE);
1603 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001604
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001605 case Intrinsic::dbg_stoppoint: {
Jim Laskey5995d012006-02-11 01:01:30 +00001606 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
Jim Laskeya8bdac82006-03-23 18:06:46 +00001607 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001608 if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001609 SDOperand Ops[5];
Chris Lattner435b4022005-11-29 06:21:05 +00001610
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001611 Ops[0] = getRoot();
1612 Ops[1] = getValue(SPI.getLineValue());
1613 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner435b4022005-11-29 06:21:05 +00001614
Jim Laskeya8bdac82006-03-23 18:06:46 +00001615 DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
Jim Laskey5995d012006-02-11 01:01:30 +00001616 assert(DD && "Not a debug information descriptor");
Jim Laskeya8bdac82006-03-23 18:06:46 +00001617 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1618
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001619 Ops[3] = DAG.getString(CompileUnit->getFileName());
1620 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskey5995d012006-02-11 01:01:30 +00001621
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001622 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001623 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001624
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001625 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001626 }
Jim Laskeya8bdac82006-03-23 18:06:46 +00001627 case Intrinsic::dbg_region_start: {
1628 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1629 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001630 if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001631 unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001632 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1633 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001634 }
1635
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001636 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001637 }
1638 case Intrinsic::dbg_region_end: {
1639 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1640 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001641 if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001642 unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001643 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1644 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001645 }
1646
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001647 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001648 }
1649 case Intrinsic::dbg_func_start: {
1650 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1651 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey70928882006-03-26 22:46:27 +00001652 if (DebugInfo && FSI.getSubprogram() &&
1653 DebugInfo->Verify(FSI.getSubprogram())) {
Jim Laskeya8bdac82006-03-23 18:06:46 +00001654 unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001655 DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1656 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskeya8bdac82006-03-23 18:06:46 +00001657 }
1658
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001659 return 0;
Jim Laskeya8bdac82006-03-23 18:06:46 +00001660 }
1661 case Intrinsic::dbg_declare: {
1662 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1663 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey67a636c2006-03-28 13:45:20 +00001664 if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
Jim Laskey53f1ecc2006-03-24 09:50:27 +00001665 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001666 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskeya8bdac82006-03-23 18:06:46 +00001667 DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskeya8bdac82006-03-23 18:06:46 +00001668 }
1669
1670 return 0;
1671 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001672
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001673 case Intrinsic::isunordered_f32:
1674 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001675 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1676 getValue(I.getOperand(2)), ISD::SETUO));
1677 return 0;
1678
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001679 case Intrinsic::sqrt_f32:
1680 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001681 setValue(&I, DAG.getNode(ISD::FSQRT,
1682 getValue(I.getOperand(1)).getValueType(),
1683 getValue(I.getOperand(1))));
1684 return 0;
Chris Lattnerf0359b32006-09-09 06:03:30 +00001685 case Intrinsic::powi_f32:
1686 case Intrinsic::powi_f64:
1687 setValue(&I, DAG.getNode(ISD::FPOWI,
1688 getValue(I.getOperand(1)).getValueType(),
1689 getValue(I.getOperand(1)),
1690 getValue(I.getOperand(2))));
1691 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001692 case Intrinsic::pcmarker: {
1693 SDOperand Tmp = getValue(I.getOperand(1));
1694 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1695 return 0;
1696 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001697 case Intrinsic::readcyclecounter: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001698 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00001699 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
1700 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
1701 &Op, 1);
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001702 setValue(&I, Tmp);
1703 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001704 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001705 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001706 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001707 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001708 case Intrinsic::bswap_i64:
1709 setValue(&I, DAG.getNode(ISD::BSWAP,
1710 getValue(I.getOperand(1)).getValueType(),
1711 getValue(I.getOperand(1))));
1712 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001713 case Intrinsic::cttz_i8:
1714 case Intrinsic::cttz_i16:
1715 case Intrinsic::cttz_i32:
1716 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001717 setValue(&I, DAG.getNode(ISD::CTTZ,
1718 getValue(I.getOperand(1)).getValueType(),
1719 getValue(I.getOperand(1))));
1720 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001721 case Intrinsic::ctlz_i8:
1722 case Intrinsic::ctlz_i16:
1723 case Intrinsic::ctlz_i32:
1724 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001725 setValue(&I, DAG.getNode(ISD::CTLZ,
1726 getValue(I.getOperand(1)).getValueType(),
1727 getValue(I.getOperand(1))));
1728 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001729 case Intrinsic::ctpop_i8:
1730 case Intrinsic::ctpop_i16:
1731 case Intrinsic::ctpop_i32:
1732 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001733 setValue(&I, DAG.getNode(ISD::CTPOP,
1734 getValue(I.getOperand(1)).getValueType(),
1735 getValue(I.getOperand(1))));
1736 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001737 case Intrinsic::stacksave: {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00001738 SDOperand Op = getRoot();
Chris Lattnerbd887772006-08-14 23:53:35 +00001739 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
1740 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattnerb3266452006-01-13 02:50:02 +00001741 setValue(&I, Tmp);
1742 DAG.setRoot(Tmp.getValue(1));
1743 return 0;
1744 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001745 case Intrinsic::stackrestore: {
1746 SDOperand Tmp = getValue(I.getOperand(1));
1747 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001748 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001749 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001750 case Intrinsic::prefetch:
1751 // FIXME: Currently discarding prefetches.
1752 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001753 }
1754}
1755
1756
Chris Lattner7a60d912005-01-07 07:47:53 +00001757void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001758 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001759 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001760 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001761 if (unsigned IID = F->getIntrinsicID()) {
1762 RenameFn = visitIntrinsicCall(I, IID);
1763 if (!RenameFn)
1764 return;
1765 } else { // Not an LLVM intrinsic.
1766 const std::string &Name = F->getName();
Chris Lattner5c1ba2a2006-03-05 05:09:38 +00001767 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1768 if (I.getNumOperands() == 3 && // Basic sanity checks.
1769 I.getOperand(1)->getType()->isFloatingPoint() &&
1770 I.getType() == I.getOperand(1)->getType() &&
1771 I.getType() == I.getOperand(2)->getType()) {
1772 SDOperand LHS = getValue(I.getOperand(1));
1773 SDOperand RHS = getValue(I.getOperand(2));
1774 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1775 LHS, RHS));
1776 return;
1777 }
1778 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001779 if (I.getNumOperands() == 2 && // Basic sanity checks.
1780 I.getOperand(1)->getType()->isFloatingPoint() &&
1781 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001782 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001783 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1784 return;
1785 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001786 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001787 if (I.getNumOperands() == 2 && // Basic sanity checks.
1788 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001789 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001790 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001791 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1792 return;
1793 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001794 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001795 if (I.getNumOperands() == 2 && // Basic sanity checks.
1796 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001797 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001798 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001799 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1800 return;
1801 }
1802 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001803 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001804 } else if (isa<InlineAsm>(I.getOperand(0))) {
1805 visitInlineAsm(I);
1806 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001807 }
Misha Brukman835702a2005-04-21 22:36:52 +00001808
Chris Lattner18d2b342005-01-08 22:48:57 +00001809 SDOperand Callee;
1810 if (!RenameFn)
1811 Callee = getValue(I.getOperand(0));
1812 else
1813 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001814 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001815 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001816 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1817 Value *Arg = I.getOperand(i);
1818 SDOperand ArgNode = getValue(Arg);
1819 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1820 }
Misha Brukman835702a2005-04-21 22:36:52 +00001821
Nate Begemanf6565252005-03-26 01:29:23 +00001822 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1823 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001824
Chris Lattner1f45cd72005-01-08 19:26:18 +00001825 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001826 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001827 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001828 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001829 setValue(&I, Result.first);
1830 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001831}
1832
Chris Lattner6f87d182006-02-22 22:37:12 +00001833SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001834 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001835 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1836 Chain = Val.getValue(1);
1837 Flag = Val.getValue(2);
1838
1839 // If the result was expanded, copy from the top part.
1840 if (Regs.size() > 1) {
1841 assert(Regs.size() == 2 &&
1842 "Cannot expand to more than 2 elts yet!");
1843 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Chengf80dfa82006-10-04 22:23:53 +00001844 Chain = Hi.getValue(1);
1845 Flag = Hi.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001846 if (DAG.getTargetLoweringInfo().isLittleEndian())
1847 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1848 else
1849 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001850 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001851
Chris Lattner705948d2006-06-08 18:22:48 +00001852 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner6f87d182006-02-22 22:37:12 +00001853 // appropriate type.
1854 if (RegVT == ValueVT)
1855 return Val;
1856
Chris Lattner705948d2006-06-08 18:22:48 +00001857 if (MVT::isInteger(RegVT)) {
1858 if (ValueVT < RegVT)
1859 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1860 else
1861 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
1862 } else {
Chris Lattner6f87d182006-02-22 22:37:12 +00001863 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattner705948d2006-06-08 18:22:48 +00001864 }
Chris Lattner6f87d182006-02-22 22:37:12 +00001865}
1866
Chris Lattner571d9642006-02-23 19:21:04 +00001867/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1868/// specified value into the registers specified by this object. This uses
1869/// Chain/Flag as the input and updates them for the output Chain/Flag.
1870void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chengef9e07d2006-06-15 08:11:54 +00001871 SDOperand &Chain, SDOperand &Flag,
1872 MVT::ValueType PtrVT) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001873 if (Regs.size() == 1) {
1874 // If there is a single register and the types differ, this must be
1875 // a promotion.
1876 if (RegVT != ValueVT) {
Chris Lattnerc03a9252006-06-08 18:27:11 +00001877 if (MVT::isInteger(RegVT)) {
1878 if (RegVT < ValueVT)
1879 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
1880 else
1881 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1882 } else
Chris Lattner571d9642006-02-23 19:21:04 +00001883 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1884 }
1885 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1886 Flag = Chain.getValue(1);
1887 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001888 std::vector<unsigned> R(Regs);
1889 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1890 std::reverse(R.begin(), R.end());
1891
1892 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001893 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chengef9e07d2006-06-15 08:11:54 +00001894 DAG.getConstant(i, PtrVT));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001895 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001896 Flag = Chain.getValue(1);
1897 }
1898 }
1899}
Chris Lattner6f87d182006-02-22 22:37:12 +00001900
Chris Lattner571d9642006-02-23 19:21:04 +00001901/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1902/// operand list. This adds the code marker and includes the number of
1903/// values added into it.
1904void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001905 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001906 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1907 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1908 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1909}
Chris Lattner6f87d182006-02-22 22:37:12 +00001910
1911/// isAllocatableRegister - If the specified register is safe to allocate,
1912/// i.e. it isn't a stack pointer or some other special register, return the
1913/// register class for the register. Otherwise, return null.
1914static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001915isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1916 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001917 MVT::ValueType FoundVT = MVT::Other;
1918 const TargetRegisterClass *FoundRC = 0;
Chris Lattnerb1124f32006-02-22 23:09:03 +00001919 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1920 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001921 MVT::ValueType ThisVT = MVT::Other;
1922
Chris Lattnerb1124f32006-02-22 23:09:03 +00001923 const TargetRegisterClass *RC = *RCI;
1924 // If none of the the value types for this register class are valid, we
1925 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001926 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1927 I != E; ++I) {
1928 if (TLI.isTypeLegal(*I)) {
Chris Lattnerbec582f2006-04-02 00:24:45 +00001929 // If we have already found this register in a different register class,
1930 // choose the one with the largest VT specified. For example, on
1931 // PowerPC, we favor f64 register classes over f32.
1932 if (FoundVT == MVT::Other ||
1933 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
1934 ThisVT = *I;
1935 break;
1936 }
Chris Lattnerb1124f32006-02-22 23:09:03 +00001937 }
1938 }
1939
Chris Lattnerbec582f2006-04-02 00:24:45 +00001940 if (ThisVT == MVT::Other) continue;
Chris Lattnerb1124f32006-02-22 23:09:03 +00001941
Chris Lattner6f87d182006-02-22 22:37:12 +00001942 // NOTE: This isn't ideal. In particular, this might allocate the
1943 // frame pointer in functions that need it (due to them not being taken
1944 // out of allocation, because a variable sized allocation hasn't been seen
1945 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001946 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1947 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerbec582f2006-04-02 00:24:45 +00001948 if (*I == Reg) {
1949 // We found a matching register class. Keep looking at others in case
1950 // we find one with larger registers that this physreg is also in.
1951 FoundRC = RC;
1952 FoundVT = ThisVT;
1953 break;
1954 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001955 }
Chris Lattnerbec582f2006-04-02 00:24:45 +00001956 return FoundRC;
Chris Lattner6f87d182006-02-22 22:37:12 +00001957}
1958
1959RegsForValue SelectionDAGLowering::
1960GetRegistersForValue(const std::string &ConstrCode,
1961 MVT::ValueType VT, bool isOutReg, bool isInReg,
1962 std::set<unsigned> &OutputRegs,
1963 std::set<unsigned> &InputRegs) {
1964 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1965 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1966 std::vector<unsigned> Regs;
1967
1968 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1969 MVT::ValueType RegVT;
1970 MVT::ValueType ValueVT = VT;
1971
1972 if (PhysReg.first) {
1973 if (VT == MVT::Other)
1974 ValueVT = *PhysReg.second->vt_begin();
Chris Lattner705948d2006-06-08 18:22:48 +00001975
1976 // Get the actual register value type. This is important, because the user
1977 // may have asked for (e.g.) the AX register in i32 type. We need to
1978 // remember that AX is actually i16 to get the right extension.
1979 RegVT = *PhysReg.second->vt_begin();
Chris Lattner6f87d182006-02-22 22:37:12 +00001980
1981 // This is a explicit reference to a physical register.
1982 Regs.push_back(PhysReg.first);
1983
1984 // If this is an expanded reference, add the rest of the regs to Regs.
1985 if (NumRegs != 1) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001986 TargetRegisterClass::iterator I = PhysReg.second->begin();
1987 TargetRegisterClass::iterator E = PhysReg.second->end();
1988 for (; *I != PhysReg.first; ++I)
1989 assert(I != E && "Didn't find reg!");
1990
1991 // Already added the first reg.
1992 --NumRegs; ++I;
1993 for (; NumRegs; --NumRegs, ++I) {
1994 assert(I != E && "Ran out of registers to allocate!");
1995 Regs.push_back(*I);
1996 }
1997 }
1998 return RegsForValue(Regs, RegVT, ValueVT);
1999 }
2000
2001 // This is a reference to a register class. Allocate NumRegs consecutive,
2002 // available, registers from the class.
2003 std::vector<unsigned> RegClassRegs =
2004 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2005
2006 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2007 MachineFunction &MF = *CurMBB->getParent();
2008 unsigned NumAllocated = 0;
2009 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2010 unsigned Reg = RegClassRegs[i];
2011 // See if this register is available.
2012 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2013 (isInReg && InputRegs.count(Reg))) { // Already used.
2014 // Make sure we find consecutive registers.
2015 NumAllocated = 0;
2016 continue;
2017 }
2018
2019 // Check to see if this register is allocatable (i.e. don't give out the
2020 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00002021 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00002022 if (!RC) {
2023 // Make sure we find consecutive registers.
2024 NumAllocated = 0;
2025 continue;
2026 }
2027
2028 // Okay, this register is good, we can use it.
2029 ++NumAllocated;
2030
2031 // If we allocated enough consecutive
2032 if (NumAllocated == NumRegs) {
2033 unsigned RegStart = (i-NumAllocated)+1;
2034 unsigned RegEnd = i+1;
2035 // Mark all of the allocated registers used.
2036 for (unsigned i = RegStart; i != RegEnd; ++i) {
2037 unsigned Reg = RegClassRegs[i];
2038 Regs.push_back(Reg);
2039 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2040 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2041 }
2042
2043 return RegsForValue(Regs, *RC->vt_begin(), VT);
2044 }
2045 }
2046
2047 // Otherwise, we couldn't allocate enough registers for this.
2048 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00002049}
2050
Chris Lattner6f87d182006-02-22 22:37:12 +00002051
Chris Lattner476e67b2006-01-26 22:24:51 +00002052/// visitInlineAsm - Handle a call to an InlineAsm object.
2053///
2054void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2055 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2056
2057 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2058 MVT::Other);
2059
2060 // Note, we treat inline asms both with and without side-effects as the same.
2061 // If an inline asm doesn't have side effects and doesn't access memory, we
2062 // could not choose to not chain it.
2063 bool hasSideEffects = IA->hasSideEffects();
2064
Chris Lattner3a5ed552006-02-01 01:28:23 +00002065 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002066 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00002067
2068 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2069 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2070 /// if it is a def of that register.
2071 std::vector<SDOperand> AsmNodeOperands;
2072 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2073 AsmNodeOperands.push_back(AsmStr);
2074
2075 SDOperand Chain = getRoot();
2076 SDOperand Flag;
2077
Chris Lattner1558fc62006-02-01 18:59:47 +00002078 // We fully assign registers here at isel time. This is not optimal, but
2079 // should work. For register classes that correspond to LLVM classes, we
2080 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2081 // over the constraints, collecting fixed registers that we know we can't use.
2082 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002083 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00002084 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2085 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2086 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00002087
Chris Lattner7ad77df2006-02-22 00:56:39 +00002088 MVT::ValueType OpVT;
2089
2090 // Compute the value type for each operand and add it to ConstraintVTs.
2091 switch (Constraints[i].Type) {
2092 case InlineAsm::isOutput:
2093 if (!Constraints[i].isIndirectOutput) {
2094 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2095 OpVT = TLI.getValueType(I.getType());
2096 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002097 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner7ad77df2006-02-22 00:56:39 +00002098 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2099 OpNum++; // Consumes a call operand.
2100 }
2101 break;
2102 case InlineAsm::isInput:
2103 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2104 OpNum++; // Consumes a call operand.
2105 break;
2106 case InlineAsm::isClobber:
2107 OpVT = MVT::Other;
2108 break;
2109 }
2110
2111 ConstraintVTs.push_back(OpVT);
2112
Chris Lattner6f87d182006-02-22 22:37:12 +00002113 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2114 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00002115
Chris Lattner6f87d182006-02-22 22:37:12 +00002116 // Build a list of regs that this operand uses. This always has a single
2117 // element for promoted/expanded operands.
2118 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2119 false, false,
2120 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00002121
2122 switch (Constraints[i].Type) {
2123 case InlineAsm::isOutput:
2124 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002125 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002126 // If this is an early-clobber output, it cannot be assigned to the same
2127 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00002128 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00002129 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002130 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002131 case InlineAsm::isInput:
2132 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00002133 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00002134 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002135 case InlineAsm::isClobber:
2136 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002137 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2138 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00002139 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00002140 }
2141 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00002142
Chris Lattner5c79f982006-02-21 23:12:12 +00002143 // Loop over all of the inputs, copying the operand values into the
2144 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00002145 RegsForValue RetValRegs;
2146 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00002147 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00002148
Chris Lattner2e56e892006-01-31 02:03:41 +00002149 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00002150 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2151 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00002152
Chris Lattner3a5ed552006-02-01 01:28:23 +00002153 switch (Constraints[i].Type) {
2154 case InlineAsm::isOutput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002155 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2156 if (ConstraintCode.size() == 1) // not a physreg name.
2157 CTy = TLI.getConstraintType(ConstraintCode[0]);
2158
2159 if (CTy == TargetLowering::C_Memory) {
2160 // Memory output.
2161 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2162
2163 // Check that the operand (the address to store to) isn't a float.
2164 if (!MVT::isInteger(InOperandVal.getValueType()))
2165 assert(0 && "MATCH FAIL!");
2166
2167 if (!Constraints[i].isIndirectOutput)
2168 assert(0 && "MATCH FAIL!");
2169
2170 OpNum++; // Consumes a call operand.
2171
2172 // Extend/truncate to the right pointer type if needed.
2173 MVT::ValueType PtrType = TLI.getPointerTy();
2174 if (InOperandVal.getValueType() < PtrType)
2175 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2176 else if (InOperandVal.getValueType() > PtrType)
2177 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2178
2179 // Add information to the INLINEASM node to know about this output.
2180 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2181 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2182 AsmNodeOperands.push_back(InOperandVal);
2183 break;
2184 }
2185
2186 // Otherwise, this is a register output.
2187 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2188
Chris Lattner6f87d182006-02-22 22:37:12 +00002189 // If this is an early-clobber output, or if there is an input
2190 // constraint that matches this, we need to reserve the input register
2191 // so no other inputs allocate to it.
2192 bool UsesInputRegister = false;
2193 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2194 UsesInputRegister = true;
2195
2196 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00002197 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00002198 RegsForValue Regs =
2199 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2200 true, UsesInputRegister,
2201 OutputRegs, InputRegs);
2202 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00002203
Chris Lattner3a5ed552006-02-01 01:28:23 +00002204 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002205 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00002206 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00002207 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00002208 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00002209 } else {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002210 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2211 I.getOperand(OpNum)));
Chris Lattner3a5ed552006-02-01 01:28:23 +00002212 OpNum++; // Consumes a call operand.
2213 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002214
2215 // Add information to the INLINEASM node to know that this register is
2216 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00002217 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002218 break;
2219 }
2220 case InlineAsm::isInput: {
Chris Lattner9fed5b62006-02-27 23:45:39 +00002221 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner1558fc62006-02-01 18:59:47 +00002222 OpNum++; // Consumes a call operand.
Chris Lattner65ad53f2006-02-04 02:16:44 +00002223
Chris Lattner7f5880b2006-02-02 00:25:23 +00002224 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2225 // If this is required to match an output register we have already set,
2226 // just use its register.
2227 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00002228
Chris Lattner571d9642006-02-23 19:21:04 +00002229 // Scan until we find the definition we already emitted of this operand.
2230 // When we find it, create a RegsForValue operand.
2231 unsigned CurOp = 2; // The first operand.
2232 for (; OperandNo; --OperandNo) {
2233 // Advance to the next operand.
2234 unsigned NumOps =
2235 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnerb0305322006-07-20 19:02:21 +00002236 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2237 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattner571d9642006-02-23 19:21:04 +00002238 "Skipped past definitions?");
2239 CurOp += (NumOps>>3)+1;
2240 }
2241
2242 unsigned NumOps =
2243 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2244 assert((NumOps & 7) == 2 /*REGDEF*/ &&
2245 "Skipped past definitions?");
2246
2247 // Add NumOps>>3 registers to MatchedRegs.
2248 RegsForValue MatchedRegs;
2249 MatchedRegs.ValueVT = InOperandVal.getValueType();
2250 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2251 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2252 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2253 MatchedRegs.Regs.push_back(Reg);
2254 }
2255
2256 // Use the produced MatchedRegs object to
Evan Chengef9e07d2006-06-15 08:11:54 +00002257 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2258 TLI.getPointerTy());
Chris Lattner571d9642006-02-23 19:21:04 +00002259 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00002260 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00002261 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00002262
2263 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2264 if (ConstraintCode.size() == 1) // not a physreg name.
2265 CTy = TLI.getConstraintType(ConstraintCode[0]);
2266
2267 if (CTy == TargetLowering::C_Other) {
2268 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2269 assert(0 && "MATCH FAIL!");
2270
2271 // Add information to the INLINEASM node to know about this input.
2272 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2273 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2274 AsmNodeOperands.push_back(InOperandVal);
2275 break;
2276 } else if (CTy == TargetLowering::C_Memory) {
2277 // Memory input.
2278
2279 // Check that the operand isn't a float.
2280 if (!MVT::isInteger(InOperandVal.getValueType()))
2281 assert(0 && "MATCH FAIL!");
2282
2283 // Extend/truncate to the right pointer type if needed.
2284 MVT::ValueType PtrType = TLI.getPointerTy();
2285 if (InOperandVal.getValueType() < PtrType)
2286 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2287 else if (InOperandVal.getValueType() > PtrType)
2288 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2289
2290 // Add information to the INLINEASM node to know about this input.
2291 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2292 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2293 AsmNodeOperands.push_back(InOperandVal);
2294 break;
2295 }
2296
2297 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2298
2299 // Copy the input into the appropriate registers.
2300 RegsForValue InRegs =
2301 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2302 false, true, OutputRegs, InputRegs);
2303 // FIXME: should be match fail.
2304 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2305
Evan Chengef9e07d2006-06-15 08:11:54 +00002306 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner7ef7a642006-02-24 01:11:24 +00002307
2308 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002309 break;
2310 }
Chris Lattner571d9642006-02-23 19:21:04 +00002311 case InlineAsm::isClobber: {
2312 RegsForValue ClobberedRegs =
2313 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2314 OutputRegs, InputRegs);
2315 // Add the clobbered value to the operand list, so that the register
2316 // allocator is aware that the physreg got clobbered.
2317 if (!ClobberedRegs.Regs.empty())
2318 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00002319 break;
2320 }
Chris Lattner571d9642006-02-23 19:21:04 +00002321 }
Chris Lattner2e56e892006-01-31 02:03:41 +00002322 }
Chris Lattner476e67b2006-01-26 22:24:51 +00002323
2324 // Finish up input operands.
2325 AsmNodeOperands[0] = Chain;
2326 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2327
Chris Lattnerbd887772006-08-14 23:53:35 +00002328 Chain = DAG.getNode(ISD::INLINEASM,
2329 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002330 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002331 Flag = Chain.getValue(1);
2332
Chris Lattner2e56e892006-01-31 02:03:41 +00002333 // If this asm returns a register value, copy the result from that register
2334 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00002335 if (!RetValRegs.Regs.empty())
2336 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00002337
Chris Lattner2e56e892006-01-31 02:03:41 +00002338 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2339
2340 // Process indirect outputs, first output all of the flagged copies out of
2341 // physregs.
2342 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00002343 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00002344 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00002345 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2346 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00002347 }
2348
2349 // Emit the non-flagged stores from the physregs.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002350 SmallVector<SDOperand, 8> OutChains;
Chris Lattner2e56e892006-01-31 02:03:41 +00002351 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Chengdf9ac472006-10-05 23:01:46 +00002352 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner2e56e892006-01-31 02:03:41 +00002353 getValue(StoresToEmit[i].second),
Evan Chengab51cf22006-10-13 21:14:26 +00002354 StoresToEmit[i].second, 0));
Chris Lattner2e56e892006-01-31 02:03:41 +00002355 if (!OutChains.empty())
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002356 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2357 &OutChains[0], OutChains.size());
Chris Lattner476e67b2006-01-26 22:24:51 +00002358 DAG.setRoot(Chain);
2359}
2360
2361
Chris Lattner7a60d912005-01-07 07:47:53 +00002362void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2363 SDOperand Src = getValue(I.getOperand(0));
2364
2365 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00002366
2367 if (IntPtr < Src.getValueType())
2368 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2369 else if (IntPtr > Src.getValueType())
2370 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00002371
2372 // Scale the source by the type size.
Owen Anderson20a631f2006-05-03 01:29:57 +00002373 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner7a60d912005-01-07 07:47:53 +00002374 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2375 Src, getIntPtrConstant(ElementSize));
2376
2377 std::vector<std::pair<SDOperand, const Type*> > Args;
Owen Anderson20a631f2006-05-03 01:29:57 +00002378 Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00002379
2380 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002381 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002382 DAG.getExternalSymbol("malloc", IntPtr),
2383 Args, DAG);
2384 setValue(&I, Result.first); // Pointers always fit in registers
2385 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002386}
2387
2388void SelectionDAGLowering::visitFree(FreeInst &I) {
2389 std::vector<std::pair<SDOperand, const Type*> > Args;
2390 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
Owen Anderson20a631f2006-05-03 01:29:57 +00002391 TLI.getTargetData()->getIntPtrType()));
Chris Lattner7a60d912005-01-07 07:47:53 +00002392 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00002393 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00002394 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00002395 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2396 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002397}
2398
Chris Lattner13d7c252005-08-26 20:54:47 +00002399// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2400// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
2401// instructions are special in various ways, which require special support to
2402// insert. The specified MachineInstr is created but not inserted into any
2403// basic blocks, and the scheduler passes ownership of it to this method.
2404MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2405 MachineBasicBlock *MBB) {
2406 std::cerr << "If a target marks an instruction with "
2407 "'usesCustomDAGSchedInserter', it must implement "
2408 "TargetLowering::InsertAtEndOfBasicBlock!\n";
2409 abort();
2410 return 0;
2411}
2412
Chris Lattner58cfd792005-01-09 00:00:49 +00002413void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002414 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2415 getValue(I.getOperand(1)),
2416 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00002417}
2418
2419void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002420 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2421 getValue(I.getOperand(0)),
2422 DAG.getSrcValue(I.getOperand(0)));
2423 setValue(&I, V);
2424 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00002425}
2426
2427void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002428 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2429 getValue(I.getOperand(1)),
2430 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002431}
2432
2433void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00002434 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2435 getValue(I.getOperand(1)),
2436 getValue(I.getOperand(2)),
2437 DAG.getSrcValue(I.getOperand(1)),
2438 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00002439}
2440
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002441/// TargetLowering::LowerArguments - This is the default LowerArguments
2442/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattneraaa23d92006-05-16 22:53:20 +00002443/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2444/// integrated into SDISel.
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002445std::vector<SDOperand>
2446TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2447 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2448 std::vector<SDOperand> Ops;
Chris Lattner3d826992006-05-16 06:45:34 +00002449 Ops.push_back(DAG.getRoot());
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002450 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2451 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2452
2453 // Add one result value for each formal argument.
2454 std::vector<MVT::ValueType> RetVals;
2455 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2456 MVT::ValueType VT = getValueType(I->getType());
2457
2458 switch (getTypeAction(VT)) {
2459 default: assert(0 && "Unknown type action!");
2460 case Legal:
2461 RetVals.push_back(VT);
2462 break;
2463 case Promote:
2464 RetVals.push_back(getTypeToTransformTo(VT));
2465 break;
2466 case Expand:
2467 if (VT != MVT::Vector) {
2468 // If this is a large integer, it needs to be broken up into small
2469 // integers. Figure out what the destination type is and how many small
2470 // integers it turns into.
2471 MVT::ValueType NVT = getTypeToTransformTo(VT);
2472 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2473 for (unsigned i = 0; i != NumVals; ++i)
2474 RetVals.push_back(NVT);
2475 } else {
2476 // Otherwise, this is a vector type. We only support legal vectors
2477 // right now.
2478 unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2479 const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002480
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002481 // Figure out if there is a Packed type corresponding to this Vector
2482 // type. If so, convert to the packed type.
2483 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2484 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2485 RetVals.push_back(TVT);
2486 } else {
2487 assert(0 && "Don't support illegal by-val vector arguments yet!");
2488 }
2489 }
2490 break;
2491 }
2492 }
Evan Cheng9618df12006-04-25 23:03:35 +00002493
Chris Lattner3d826992006-05-16 06:45:34 +00002494 RetVals.push_back(MVT::Other);
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002495
2496 // Create the node.
Chris Lattnerbd887772006-08-14 23:53:35 +00002497 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2498 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002499 &Ops[0], Ops.size()).Val;
Chris Lattner3d826992006-05-16 06:45:34 +00002500
2501 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002502
2503 // Set up the return result vector.
2504 Ops.clear();
2505 unsigned i = 0;
2506 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2507 MVT::ValueType VT = getValueType(I->getType());
2508
2509 switch (getTypeAction(VT)) {
2510 default: assert(0 && "Unknown type action!");
2511 case Legal:
2512 Ops.push_back(SDOperand(Result, i++));
2513 break;
2514 case Promote: {
2515 SDOperand Op(Result, i++);
2516 if (MVT::isInteger(VT)) {
2517 unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2518 : ISD::AssertZext;
2519 Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2520 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2521 } else {
2522 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2523 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2524 }
2525 Ops.push_back(Op);
2526 break;
2527 }
2528 case Expand:
2529 if (VT != MVT::Vector) {
2530 // If this is a large integer, it needs to be reassembled from small
2531 // integers. Figure out what the source elt type is and how many small
2532 // integers it is.
2533 MVT::ValueType NVT = getTypeToTransformTo(VT);
2534 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2535 if (NumVals == 2) {
2536 SDOperand Lo = SDOperand(Result, i++);
2537 SDOperand Hi = SDOperand(Result, i++);
2538
2539 if (!isLittleEndian())
2540 std::swap(Lo, Hi);
2541
2542 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2543 } else {
2544 // Value scalarized into many values. Unimp for now.
2545 assert(0 && "Cannot expand i64 -> i16 yet!");
2546 }
2547 } else {
2548 // Otherwise, this is a vector type. We only support legal vectors
2549 // right now.
Evan Chengd43c5c62006-04-28 05:25:15 +00002550 const PackedType *PTy = cast<PackedType>(I->getType());
2551 unsigned NumElems = PTy->getNumElements();
2552 const Type *EltTy = PTy->getElementType();
Evan Cheng3784f3c52006-04-27 08:29:42 +00002553
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002554 // Figure out if there is a Packed type corresponding to this Vector
2555 // type. If so, convert to the packed type.
2556 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner7949c2e2006-05-17 20:49:36 +00002557 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Chengd43c5c62006-04-28 05:25:15 +00002558 SDOperand N = SDOperand(Result, i++);
2559 // Handle copies from generic vectors to registers.
Chris Lattner7949c2e2006-05-17 20:49:36 +00002560 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2561 DAG.getConstant(NumElems, MVT::i32),
2562 DAG.getValueType(getValueType(EltTy)));
2563 Ops.push_back(N);
2564 } else {
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002565 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerb77ba732006-05-16 23:39:44 +00002566 abort();
Chris Lattnerd3b504a2006-04-12 16:20:43 +00002567 }
2568 }
2569 break;
2570 }
2571 }
2572 return Ops;
2573}
2574
Chris Lattneraaa23d92006-05-16 22:53:20 +00002575
2576/// TargetLowering::LowerCallTo - This is the default LowerCallTo
2577/// implementation, which just inserts an ISD::CALL node, which is later custom
2578/// lowered by the target to something concrete. FIXME: When all targets are
2579/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2580std::pair<SDOperand, SDOperand>
2581TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2582 unsigned CallingConv, bool isTailCall,
2583 SDOperand Callee,
2584 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattner65879ca2006-08-16 22:57:46 +00002585 SmallVector<SDOperand, 32> Ops;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002586 Ops.push_back(Chain); // Op#0 - Chain
2587 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2588 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
2589 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
2590 Ops.push_back(Callee);
2591
2592 // Handle all of the outgoing arguments.
2593 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2594 MVT::ValueType VT = getValueType(Args[i].second);
2595 SDOperand Op = Args[i].first;
Evan Cheng45827712006-05-25 00:55:32 +00002596 bool isSigned = Args[i].second->isSigned();
Chris Lattneraaa23d92006-05-16 22:53:20 +00002597 switch (getTypeAction(VT)) {
2598 default: assert(0 && "Unknown type action!");
2599 case Legal:
2600 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002601 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002602 break;
2603 case Promote:
2604 if (MVT::isInteger(VT)) {
Evan Cheng45827712006-05-25 00:55:32 +00002605 unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002606 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2607 } else {
2608 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2609 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2610 }
2611 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002612 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002613 break;
2614 case Expand:
2615 if (VT != MVT::Vector) {
2616 // If this is a large integer, it needs to be broken down into small
2617 // integers. Figure out what the source elt type is and how many small
2618 // integers it is.
2619 MVT::ValueType NVT = getTypeToTransformTo(VT);
2620 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2621 if (NumVals == 2) {
2622 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2623 DAG.getConstant(0, getPointerTy()));
2624 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2625 DAG.getConstant(1, getPointerTy()));
2626 if (!isLittleEndian())
2627 std::swap(Lo, Hi);
2628
2629 Ops.push_back(Lo);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002630 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002631 Ops.push_back(Hi);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002632 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattneraaa23d92006-05-16 22:53:20 +00002633 } else {
2634 // Value scalarized into many values. Unimp for now.
2635 assert(0 && "Cannot expand i64 -> i16 yet!");
2636 }
2637 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002638 // Otherwise, this is a vector type. We only support legal vectors
2639 // right now.
2640 const PackedType *PTy = cast<PackedType>(Args[i].second);
2641 unsigned NumElems = PTy->getNumElements();
2642 const Type *EltTy = PTy->getElementType();
2643
2644 // Figure out if there is a Packed type corresponding to this Vector
2645 // type. If so, convert to the packed type.
2646 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner938155c2006-05-17 20:43:21 +00002647 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2648 // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2649 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2650 Ops.push_back(Op);
Evan Cheng21dee4e2006-05-26 23:13:20 +00002651 Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
Chris Lattner938155c2006-05-17 20:43:21 +00002652 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002653 assert(0 && "Don't support illegal by-val vector call args yet!");
2654 abort();
2655 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002656 }
2657 break;
2658 }
2659 }
2660
2661 // Figure out the result value types.
Chris Lattner65879ca2006-08-16 22:57:46 +00002662 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattneraaa23d92006-05-16 22:53:20 +00002663
2664 if (RetTy != Type::VoidTy) {
2665 MVT::ValueType VT = getValueType(RetTy);
2666 switch (getTypeAction(VT)) {
2667 default: assert(0 && "Unknown type action!");
2668 case Legal:
2669 RetTys.push_back(VT);
2670 break;
2671 case Promote:
2672 RetTys.push_back(getTypeToTransformTo(VT));
2673 break;
2674 case Expand:
2675 if (VT != MVT::Vector) {
2676 // If this is a large integer, it needs to be reassembled from small
2677 // integers. Figure out what the source elt type is and how many small
2678 // integers it is.
2679 MVT::ValueType NVT = getTypeToTransformTo(VT);
2680 unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2681 for (unsigned i = 0; i != NumVals; ++i)
2682 RetTys.push_back(NVT);
2683 } else {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002684 // Otherwise, this is a vector type. We only support legal vectors
2685 // right now.
2686 const PackedType *PTy = cast<PackedType>(RetTy);
2687 unsigned NumElems = PTy->getNumElements();
2688 const Type *EltTy = PTy->getElementType();
2689
2690 // Figure out if there is a Packed type corresponding to this Vector
2691 // type. If so, convert to the packed type.
2692 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2693 if (TVT != MVT::Other && isTypeLegal(TVT)) {
2694 RetTys.push_back(TVT);
2695 } else {
2696 assert(0 && "Don't support illegal by-val vector call results yet!");
2697 abort();
2698 }
Chris Lattneraaa23d92006-05-16 22:53:20 +00002699 }
2700 }
2701 }
2702
2703 RetTys.push_back(MVT::Other); // Always has a chain.
2704
2705 // Finally, create the CALL node.
Chris Lattner65879ca2006-08-16 22:57:46 +00002706 SDOperand Res = DAG.getNode(ISD::CALL,
2707 DAG.getVTList(&RetTys[0], RetTys.size()),
2708 &Ops[0], Ops.size());
Chris Lattneraaa23d92006-05-16 22:53:20 +00002709
2710 // This returns a pair of operands. The first element is the
2711 // return value for the function (if RetTy is not VoidTy). The second
2712 // element is the outgoing token chain.
2713 SDOperand ResVal;
2714 if (RetTys.size() != 1) {
2715 MVT::ValueType VT = getValueType(RetTy);
2716 if (RetTys.size() == 2) {
2717 ResVal = Res;
2718
2719 // If this value was promoted, truncate it down.
2720 if (ResVal.getValueType() != VT) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002721 if (VT == MVT::Vector) {
2722 // Insert a VBITCONVERT to convert from the packed result type to the
2723 // MVT::Vector type.
2724 unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
2725 const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
2726
2727 // Figure out if there is a Packed type corresponding to this Vector
2728 // type. If so, convert to the packed type.
2729 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2730 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerb77ba732006-05-16 23:39:44 +00002731 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2732 // "N x PTyElementVT" MVT::Vector type.
2733 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattner7949c2e2006-05-17 20:49:36 +00002734 DAG.getConstant(NumElems, MVT::i32),
2735 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerb77ba732006-05-16 23:39:44 +00002736 } else {
2737 abort();
2738 }
2739 } else if (MVT::isInteger(VT)) {
Chris Lattneraaa23d92006-05-16 22:53:20 +00002740 unsigned AssertOp = RetTy->isSigned() ?
2741 ISD::AssertSext : ISD::AssertZext;
2742 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
2743 DAG.getValueType(VT));
2744 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
2745 } else {
2746 assert(MVT::isFloatingPoint(VT));
2747 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
2748 }
2749 }
2750 } else if (RetTys.size() == 3) {
2751 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
2752 Res.getValue(0), Res.getValue(1));
2753
2754 } else {
2755 assert(0 && "Case not handled yet!");
2756 }
2757 }
2758
2759 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
2760}
2761
2762
2763
Chris Lattner58cfd792005-01-09 00:00:49 +00002764// It is always conservatively correct for llvm.returnaddress and
2765// llvm.frameaddress to return 0.
Chris Lattneraaa23d92006-05-16 22:53:20 +00002766//
2767// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
2768// expanded to 0 if the target wants.
Chris Lattner58cfd792005-01-09 00:00:49 +00002769std::pair<SDOperand, SDOperand>
2770TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2771 unsigned Depth, SelectionDAG &DAG) {
2772 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00002773}
2774
Chris Lattner29dcc712005-05-14 05:50:48 +00002775SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00002776 assert(0 && "LowerOperation not implemented for this target!");
2777 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00002778 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00002779}
2780
Nate Begeman595ec732006-01-28 03:14:31 +00002781SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2782 SelectionDAG &DAG) {
2783 assert(0 && "CustomPromoteOperation not implemented for this target!");
2784 abort();
2785 return SDOperand();
2786}
2787
Chris Lattner58cfd792005-01-09 00:00:49 +00002788void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00002789 unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
Chris Lattner58cfd792005-01-09 00:00:49 +00002790 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00002791 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00002792 setValue(&I, Result.first);
2793 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00002794}
2795
Evan Cheng6781b6e2006-02-15 21:59:04 +00002796/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00002797/// operand.
2798static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00002799 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002800 MVT::ValueType CurVT = VT;
2801 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2802 uint64_t Val = C->getValue() & 255;
2803 unsigned Shift = 8;
2804 while (CurVT != MVT::i8) {
2805 Val = (Val << Shift) | Val;
2806 Shift <<= 1;
2807 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002808 }
2809 return DAG.getConstant(Val, VT);
2810 } else {
2811 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2812 unsigned Shift = 8;
2813 while (CurVT != MVT::i8) {
2814 Value =
2815 DAG.getNode(ISD::OR, VT,
2816 DAG.getNode(ISD::SHL, VT, Value,
2817 DAG.getConstant(Shift, MVT::i8)), Value);
2818 Shift <<= 1;
2819 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002820 }
2821
2822 return Value;
2823 }
2824}
2825
Evan Cheng6781b6e2006-02-15 21:59:04 +00002826/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2827/// used when a memcpy is turned into a memset when the source is a constant
2828/// string ptr.
2829static SDOperand getMemsetStringVal(MVT::ValueType VT,
2830 SelectionDAG &DAG, TargetLowering &TLI,
2831 std::string &Str, unsigned Offset) {
2832 MVT::ValueType CurVT = VT;
2833 uint64_t Val = 0;
2834 unsigned MSB = getSizeInBits(VT) / 8;
2835 if (TLI.isLittleEndian())
2836 Offset = Offset + MSB - 1;
2837 for (unsigned i = 0; i != MSB; ++i) {
2838 Val = (Val << 8) | Str[Offset];
2839 Offset += TLI.isLittleEndian() ? -1 : 1;
2840 }
2841 return DAG.getConstant(Val, VT);
2842}
2843
Evan Cheng81fcea82006-02-14 08:22:34 +00002844/// getMemBasePlusOffset - Returns base and offset node for the
2845static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2846 SelectionDAG &DAG, TargetLowering &TLI) {
2847 MVT::ValueType VT = Base.getValueType();
2848 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2849}
2850
Evan Chengdb2a7a72006-02-14 20:12:38 +00002851/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00002852/// to replace the memset / memcpy is below the threshold. It also returns the
2853/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00002854static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2855 unsigned Limit, uint64_t Size,
2856 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002857 MVT::ValueType VT;
2858
2859 if (TLI.allowsUnalignedMemoryAccesses()) {
2860 VT = MVT::i64;
2861 } else {
2862 switch (Align & 7) {
2863 case 0:
2864 VT = MVT::i64;
2865 break;
2866 case 4:
2867 VT = MVT::i32;
2868 break;
2869 case 2:
2870 VT = MVT::i16;
2871 break;
2872 default:
2873 VT = MVT::i8;
2874 break;
2875 }
2876 }
2877
Evan Chengd5026102006-02-14 09:11:59 +00002878 MVT::ValueType LVT = MVT::i64;
2879 while (!TLI.isTypeLegal(LVT))
2880 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2881 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00002882
Evan Chengd5026102006-02-14 09:11:59 +00002883 if (VT > LVT)
2884 VT = LVT;
2885
Evan Cheng04514992006-02-14 23:05:54 +00002886 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00002887 while (Size != 0) {
2888 unsigned VTSize = getSizeInBits(VT) / 8;
2889 while (VTSize > Size) {
2890 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00002891 VTSize >>= 1;
2892 }
Evan Chengd5026102006-02-14 09:11:59 +00002893 assert(MVT::isInteger(VT));
2894
2895 if (++NumMemOps > Limit)
2896 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00002897 MemOps.push_back(VT);
2898 Size -= VTSize;
2899 }
Evan Chengd5026102006-02-14 09:11:59 +00002900
2901 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00002902}
2903
Chris Lattner875def92005-01-11 05:56:49 +00002904void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00002905 SDOperand Op1 = getValue(I.getOperand(1));
2906 SDOperand Op2 = getValue(I.getOperand(2));
2907 SDOperand Op3 = getValue(I.getOperand(3));
2908 SDOperand Op4 = getValue(I.getOperand(4));
2909 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2910 if (Align == 0) Align = 1;
2911
2912 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2913 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00002914
2915 // Expand memset / memcpy to a series of load / store ops
2916 // if the size operand falls below a certain threshold.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002917 SmallVector<SDOperand, 8> OutChains;
Evan Cheng81fcea82006-02-14 08:22:34 +00002918 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00002919 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00002920 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00002921 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2922 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00002923 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00002924 unsigned Offset = 0;
2925 for (unsigned i = 0; i < NumMemOps; i++) {
2926 MVT::ValueType VT = MemOps[i];
2927 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00002928 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengdf9ac472006-10-05 23:01:46 +00002929 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00002930 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00002931 I.getOperand(1), Offset);
Evan Chenge2038bd2006-02-15 01:54:51 +00002932 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00002933 Offset += VTSize;
2934 }
Evan Cheng81fcea82006-02-14 08:22:34 +00002935 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002936 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00002937 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002938 case ISD::MEMCPY: {
2939 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2940 Size->getValue(), Align, TLI)) {
2941 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002942 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002943 GlobalAddressSDNode *G = NULL;
2944 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002945 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002946
2947 if (Op2.getOpcode() == ISD::GlobalAddress)
2948 G = cast<GlobalAddressSDNode>(Op2);
2949 else if (Op2.getOpcode() == ISD::ADD &&
2950 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2951 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2952 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002953 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00002954 }
2955 if (G) {
2956 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002957 if (GV) {
Evan Cheng38280c02006-03-10 23:52:03 +00002958 Str = GV->getStringValue(false);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002959 if (!Str.empty()) {
2960 CopyFromStr = true;
2961 SrcOff += SrcDelta;
2962 }
2963 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00002964 }
2965
Evan Chenge2038bd2006-02-15 01:54:51 +00002966 for (unsigned i = 0; i < NumMemOps; i++) {
2967 MVT::ValueType VT = MemOps[i];
2968 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00002969 SDOperand Value, Chain, Store;
2970
Evan Chengc3dcf5a2006-02-16 23:11:42 +00002971 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00002972 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2973 Chain = getRoot();
2974 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00002975 DAG.getStore(Chain, Value,
2976 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00002977 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002978 } else {
2979 Value = DAG.getLoad(VT, getRoot(),
2980 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Chenge71fe34d2006-10-09 20:57:25 +00002981 I.getOperand(2), SrcOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002982 Chain = Value.getValue(1);
2983 Store =
Evan Chengdf9ac472006-10-05 23:01:46 +00002984 DAG.getStore(Chain, Value,
2985 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Chengab51cf22006-10-13 21:14:26 +00002986 I.getOperand(1), DstOff);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002987 }
Evan Chenge2038bd2006-02-15 01:54:51 +00002988 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00002989 SrcOff += VTSize;
2990 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00002991 }
2992 }
2993 break;
2994 }
2995 }
2996
2997 if (!OutChains.empty()) {
Chris Lattnerc24a1d32006-08-08 02:23:42 +00002998 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
2999 &OutChains[0], OutChains.size()));
Evan Chenge2038bd2006-02-15 01:54:51 +00003000 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00003001 }
3002 }
3003
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003004 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner7a60d912005-01-07 07:47:53 +00003005}
3006
Chris Lattner875def92005-01-11 05:56:49 +00003007//===----------------------------------------------------------------------===//
3008// SelectionDAGISel code
3009//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00003010
3011unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3012 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3013}
3014
Chris Lattnerc9950c12005-08-17 06:37:43 +00003015void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00003016 // FIXME: we only modify the CFG to split critical edges. This
3017 // updates dom and loop info.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003018 AU.addRequired<AliasAnalysis>();
Chris Lattnerc9950c12005-08-17 06:37:43 +00003019}
Chris Lattner7a60d912005-01-07 07:47:53 +00003020
Chris Lattner35397782005-12-05 07:10:48 +00003021
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003022/// OptimizeNoopCopyExpression - We have determined that the specified cast
3023/// instruction is a noop copy (e.g. it's casting from one pointer type to
3024/// another, int->uint, or int->sbyte on PPC.
3025///
3026/// Return true if any changes are made.
3027static bool OptimizeNoopCopyExpression(CastInst *CI) {
3028 BasicBlock *DefBB = CI->getParent();
3029
3030 /// InsertedCasts - Only insert a cast in each block once.
3031 std::map<BasicBlock*, CastInst*> InsertedCasts;
3032
3033 bool MadeChange = false;
3034 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3035 UI != E; ) {
3036 Use &TheUse = UI.getUse();
3037 Instruction *User = cast<Instruction>(*UI);
3038
3039 // Figure out which BB this cast is used in. For PHI's this is the
3040 // appropriate predecessor block.
3041 BasicBlock *UserBB = User->getParent();
3042 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3043 unsigned OpVal = UI.getOperandNo()/2;
3044 UserBB = PN->getIncomingBlock(OpVal);
3045 }
3046
3047 // Preincrement use iterator so we don't invalidate it.
3048 ++UI;
3049
3050 // If this user is in the same block as the cast, don't change the cast.
3051 if (UserBB == DefBB) continue;
3052
3053 // If we have already inserted a cast into this block, use it.
3054 CastInst *&InsertedCast = InsertedCasts[UserBB];
3055
3056 if (!InsertedCast) {
3057 BasicBlock::iterator InsertPt = UserBB->begin();
3058 while (isa<PHINode>(InsertPt)) ++InsertPt;
3059
3060 InsertedCast =
3061 new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3062 MadeChange = true;
3063 }
3064
3065 // Replace a use of the cast with a use of the new casat.
3066 TheUse = InsertedCast;
3067 }
3068
3069 // If we removed all uses, nuke the cast.
3070 if (CI->use_empty())
3071 CI->eraseFromParent();
3072
3073 return MadeChange;
3074}
3075
Chris Lattner35397782005-12-05 07:10:48 +00003076/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3077/// casting to the type of GEPI.
Chris Lattner21cd9902006-05-06 09:10:37 +00003078static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3079 Instruction *GEPI, Value *Ptr,
3080 Value *PtrOffset) {
Chris Lattner35397782005-12-05 07:10:48 +00003081 if (V) return V; // Already computed.
3082
3083 BasicBlock::iterator InsertPt;
3084 if (BB == GEPI->getParent()) {
3085 // If insert into the GEP's block, insert right after the GEP.
3086 InsertPt = GEPI;
3087 ++InsertPt;
3088 } else {
3089 // Otherwise, insert at the top of BB, after any PHI nodes
3090 InsertPt = BB->begin();
3091 while (isa<PHINode>(InsertPt)) ++InsertPt;
3092 }
3093
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003094 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3095 // BB so that there is only one value live across basic blocks (the cast
3096 // operand).
3097 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3098 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3099 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3100
Chris Lattner35397782005-12-05 07:10:48 +00003101 // Add the offset, cast it to the right type.
3102 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Chris Lattner21cd9902006-05-06 09:10:37 +00003103 return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
Chris Lattner35397782005-12-05 07:10:48 +00003104}
3105
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003106/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3107/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3108/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3109/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3110/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3111/// the constant add into a load or store instruction. Additionally, if a user
3112/// is a pointer-pointer cast, we look through it to find its users.
3113static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3114 Constant *PtrOffset, BasicBlock *DefBB,
3115 GetElementPtrInst *GEPI,
Chris Lattner21cd9902006-05-06 09:10:37 +00003116 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003117 while (!RepPtr->use_empty()) {
3118 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003119
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003120 // If the user is a Pointer-Pointer cast, recurse.
3121 if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3122 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003123
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003124 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3125 // could invalidate an iterator.
3126 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3127 continue;
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003128 }
3129
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003130 // If this is a load of the pointer, or a store through the pointer, emit
3131 // the increment into the load/store block.
Chris Lattner21cd9902006-05-06 09:10:37 +00003132 Instruction *NewVal;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003133 if (isa<LoadInst>(User) ||
3134 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3135 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3136 User->getParent(), GEPI,
3137 Ptr, PtrOffset);
3138 } else {
3139 // If this use is not foldable into the addressing mode, use a version
3140 // emitted in the GEP block.
3141 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3142 Ptr, PtrOffset);
3143 }
3144
Chris Lattner21cd9902006-05-06 09:10:37 +00003145 if (GEPI->getType() != RepPtr->getType()) {
3146 BasicBlock::iterator IP = NewVal;
3147 ++IP;
3148 NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3149 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003150 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003151 }
3152}
Chris Lattner35397782005-12-05 07:10:48 +00003153
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003154
Chris Lattner35397782005-12-05 07:10:48 +00003155/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3156/// selection, we want to be a bit careful about some things. In particular, if
3157/// we have a GEP instruction that is used in a different block than it is
3158/// defined, the addressing expression of the GEP cannot be folded into loads or
3159/// stores that use it. In this case, decompose the GEP and move constant
3160/// indices into blocks that use it.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003161static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Anderson20a631f2006-05-03 01:29:57 +00003162 const TargetData *TD) {
Chris Lattner35397782005-12-05 07:10:48 +00003163 // If this GEP is only used inside the block it is defined in, there is no
3164 // need to rewrite it.
3165 bool isUsedOutsideDefBB = false;
3166 BasicBlock *DefBB = GEPI->getParent();
3167 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3168 UI != E; ++UI) {
3169 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3170 isUsedOutsideDefBB = true;
3171 break;
3172 }
3173 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003174 if (!isUsedOutsideDefBB) return false;
Chris Lattner35397782005-12-05 07:10:48 +00003175
3176 // If this GEP has no non-zero constant indices, there is nothing we can do,
3177 // ignore it.
3178 bool hasConstantIndex = false;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003179 bool hasVariableIndex = false;
Chris Lattner35397782005-12-05 07:10:48 +00003180 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3181 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003182 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003183 if (CI->getZExtValue()) {
Chris Lattner35397782005-12-05 07:10:48 +00003184 hasConstantIndex = true;
3185 break;
3186 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003187 } else {
3188 hasVariableIndex = true;
3189 }
Chris Lattner35397782005-12-05 07:10:48 +00003190 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003191
3192 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3193 if (!hasConstantIndex && !hasVariableIndex) {
3194 Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3195 GEPI->getName(), GEPI);
3196 GEPI->replaceAllUsesWith(NC);
3197 GEPI->eraseFromParent();
3198 return true;
3199 }
3200
Chris Lattnerf1a54c02005-12-11 09:05:13 +00003201 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003202 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3203 return false;
Chris Lattner35397782005-12-05 07:10:48 +00003204
3205 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3206 // constant offset (which we now know is non-zero) and deal with it later.
3207 uint64_t ConstantOffset = 0;
Owen Anderson20a631f2006-05-03 01:29:57 +00003208 const Type *UIntPtrTy = TD->getIntPtrType();
Chris Lattner35397782005-12-05 07:10:48 +00003209 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3210 const Type *Ty = GEPI->getOperand(0)->getType();
3211
3212 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3213 E = GEPI->op_end(); OI != E; ++OI) {
3214 Value *Idx = *OI;
3215 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003216 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003217 if (Field)
Owen Anderson20a631f2006-05-03 01:29:57 +00003218 ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
Chris Lattner35397782005-12-05 07:10:48 +00003219 Ty = StTy->getElementType(Field);
3220 } else {
3221 Ty = cast<SequentialType>(Ty)->getElementType();
3222
3223 // Handle constant subscripts.
3224 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00003225 if (CI->getZExtValue() == 0) continue;
3226 if (CI->getType()->isSigned())
3227 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003228 else
Reid Spencere0fc4df2006-10-20 07:07:24 +00003229 ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
Chris Lattner35397782005-12-05 07:10:48 +00003230 continue;
3231 }
3232
3233 // Ptr = Ptr + Idx * ElementSize;
3234
3235 // Cast Idx to UIntPtrTy if needed.
3236 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3237
Owen Anderson20a631f2006-05-03 01:29:57 +00003238 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner35397782005-12-05 07:10:48 +00003239 // Mask off bits that should not be set.
3240 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003241 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattner35397782005-12-05 07:10:48 +00003242
3243 // Multiply by the element size and add to the base.
3244 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3245 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3246 }
3247 }
3248
3249 // Make sure that the offset fits in uintptr_t.
3250 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencere0fc4df2006-10-20 07:07:24 +00003251 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattner35397782005-12-05 07:10:48 +00003252
3253 // Okay, we have now emitted all of the variable index parts to the BB that
3254 // the GEP is defined in. Loop over all of the using instructions, inserting
3255 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00003256 // instruction to use the newly computed value, making GEPI dead. When the
3257 // user is a load or store instruction address, we emit the add into the user
3258 // block, otherwise we use a canonical version right next to the gep (these
3259 // won't be foldable as addresses, so we might as well share the computation).
3260
Chris Lattner21cd9902006-05-06 09:10:37 +00003261 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003262 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner35397782005-12-05 07:10:48 +00003263
3264 // Finally, the GEP is dead, remove it.
3265 GEPI->eraseFromParent();
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003266
3267 return true;
Chris Lattner35397782005-12-05 07:10:48 +00003268}
3269
Chris Lattnera9caf952006-09-28 06:17:10 +00003270/// SplitCritEdgesForPHIConstants - If this block has any PHI nodes with
3271/// constant operands, and if any of the edges feeding the PHI node are
3272/// critical, split them so that the assignments of a constant to a register
3273/// will not be executed on a path that isn't relevant.
3274void SelectionDAGISel::SplitCritEdgesForPHIConstants(BasicBlock *BB) {
Chris Lattner6df34962006-10-11 03:58:02 +00003275 // The most common case is that this is a PHI node with two incoming
3276 // successors handle this case efficiently, because it is simple.
3277 PHINode *PN = cast<PHINode>(BB->begin());
3278 if (PN->getNumIncomingValues() == 2) {
3279 // If neither edge is critical, we never need to split.
3280 if (PN->getIncomingBlock(0)->getTerminator()->getNumSuccessors() == 1 &&
3281 PN->getIncomingBlock(1)->getTerminator()->getNumSuccessors() == 1)
3282 return;
3283
3284 BasicBlock::iterator BBI = BB->begin();
3285 while ((PN = dyn_cast<PHINode>(BBI++))) {
3286 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3287 if (isa<Constant>(PN->getIncomingValue(i)))
3288 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3289 }
3290 return;
3291 }
3292
3293 // Otherwise, things are a bit trickier.
3294
3295 // BE SMART HERE.
3296
Chris Lattnera9caf952006-09-28 06:17:10 +00003297 BasicBlock::iterator BBI = BB->begin();
3298 while ((PN = dyn_cast<PHINode>(BBI++))) {
3299 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3300 if (isa<Constant>(PN->getIncomingValue(i)))
3301 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
3302 }
3303}
3304
3305
Chris Lattner7a60d912005-01-07 07:47:53 +00003306bool SelectionDAGISel::runOnFunction(Function &Fn) {
3307 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3308 RegMap = MF.getSSARegMap();
3309 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3310
Chris Lattner35397782005-12-05 07:10:48 +00003311 // First, split all critical edges for PHI nodes with incoming values that are
3312 // constants, this way the load of the constant into a vreg will not be placed
3313 // into MBBs that are used some other way.
3314 //
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003315 // In this pass we also look for GEP and cast instructions that are used
3316 // across basic blocks and rewrite them to improve basic-block-at-a-time
3317 // selection.
3318 //
Chris Lattner35397782005-12-05 07:10:48 +00003319 //
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003320 bool MadeChange = true;
3321 while (MadeChange) {
3322 MadeChange = false;
Chris Lattner1a908c82005-08-18 17:35:14 +00003323 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
Chris Lattnera9caf952006-09-28 06:17:10 +00003324 // If this block has any PHI nodes with constant operands, and if any of the
3325 // edges feeding the PHI node are critical, split them.
3326 if (isa<PHINode>(BB->begin()))
3327 SplitCritEdgesForPHIConstants(BB);
Chris Lattner35397782005-12-05 07:10:48 +00003328
Chris Lattnera9caf952006-09-28 06:17:10 +00003329 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003330 Instruction *I = BBI++;
3331 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003332 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003333 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattner84cc1f72006-09-13 06:02:42 +00003334 // If the source of the cast is a constant, then this should have
3335 // already been constant folded. The only reason NOT to constant fold
3336 // it is if something (e.g. LSR) was careful to place the constant
3337 // evaluation in a block other than then one that uses it (e.g. to hoist
3338 // the address of globals out of a loop). If this is the case, we don't
3339 // want to forward-subst the cast.
3340 if (isa<Constant>(CI->getOperand(0)))
3341 continue;
3342
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003343 // If this is a noop copy, sink it into user blocks to reduce the number
3344 // of virtual registers that must be created and coallesced.
3345 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3346 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3347
3348 // This is an fp<->int conversion?
3349 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3350 continue;
3351
3352 // If this is an extension, it will be a zero or sign extension, which
3353 // isn't a noop.
3354 if (SrcVT < DstVT) continue;
3355
3356 // If these values will be promoted, find out what they will be promoted
3357 // to. This helps us consider truncates on PPC as noop copies when they
3358 // are.
3359 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3360 SrcVT = TLI.getTypeToTransformTo(SrcVT);
3361 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3362 DstVT = TLI.getTypeToTransformTo(DstVT);
3363
3364 // If, after promotion, these are the same types, this is a noop copy.
3365 if (SrcVT == DstVT)
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003366 MadeChange |= OptimizeNoopCopyExpression(CI);
Chris Lattner7a3ecf72006-05-05 01:04:50 +00003367 }
3368 }
Chris Lattner1a908c82005-08-18 17:35:14 +00003369 }
Chris Lattner3e3f2c62006-05-05 21:17:49 +00003370 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00003371
Chris Lattner7a60d912005-01-07 07:47:53 +00003372 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3373
3374 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3375 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00003376
Chris Lattner7a60d912005-01-07 07:47:53 +00003377 return true;
3378}
3379
3380
Chris Lattner718b5c22005-01-13 17:59:43 +00003381SDOperand SelectionDAGISel::
3382CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00003383 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00003384 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00003385 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00003386 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00003387
3388 // If this type is not legal, we must make sure to not create an invalid
3389 // register use.
3390 MVT::ValueType SrcVT = Op.getValueType();
3391 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3392 SelectionDAG &DAG = SDL.DAG;
3393 if (SrcVT == DestVT) {
3394 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
Chris Lattner672a42d2006-03-21 19:20:37 +00003395 } else if (SrcVT == MVT::Vector) {
Chris Lattner5fe1f542006-03-31 02:06:56 +00003396 // Handle copies from generic vectors to registers.
3397 MVT::ValueType PTyElementVT, PTyLegalElementVT;
3398 unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3399 PTyElementVT, PTyLegalElementVT);
Chris Lattner672a42d2006-03-21 19:20:37 +00003400
Chris Lattner5fe1f542006-03-31 02:06:56 +00003401 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3402 // MVT::Vector type.
3403 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3404 DAG.getConstant(NE, MVT::i32),
3405 DAG.getValueType(PTyElementVT));
Chris Lattner672a42d2006-03-21 19:20:37 +00003406
Chris Lattner5fe1f542006-03-31 02:06:56 +00003407 // Loop over all of the elements of the resultant vector,
3408 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3409 // copying them into output registers.
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003410 SmallVector<SDOperand, 8> OutChains;
Chris Lattner5fe1f542006-03-31 02:06:56 +00003411 SDOperand Root = SDL.getRoot();
3412 for (unsigned i = 0; i != NE; ++i) {
3413 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003414 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003415 if (PTyElementVT == PTyLegalElementVT) {
3416 // Elements are legal.
3417 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3418 } else if (PTyLegalElementVT > PTyElementVT) {
3419 // Elements are promoted.
3420 if (MVT::isFloatingPoint(PTyLegalElementVT))
3421 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3422 else
3423 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3424 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3425 } else {
3426 // Elements are expanded.
3427 // The src value is expanded into multiple registers.
3428 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003429 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003430 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003431 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner5fe1f542006-03-31 02:06:56 +00003432 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3433 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3434 }
Chris Lattner672a42d2006-03-21 19:20:37 +00003435 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003436 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3437 &OutChains[0], OutChains.size());
Chris Lattner33182322005-08-16 21:55:35 +00003438 } else if (SrcVT < DestVT) {
3439 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00003440 if (MVT::isFloatingPoint(SrcVT))
3441 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3442 else
Chris Lattnera66403d2005-09-02 00:19:37 +00003443 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00003444 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
3445 } else {
3446 // The src value is expanded into multiple registers.
3447 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003448 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003449 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chengef9e07d2006-06-15 08:11:54 +00003450 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner33182322005-08-16 21:55:35 +00003451 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
3452 return DAG.getCopyToReg(Op, Reg+1, Hi);
3453 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003454}
3455
Chris Lattner16f64df2005-01-17 17:15:02 +00003456void SelectionDAGISel::
3457LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3458 std::vector<SDOperand> &UnorderedChains) {
3459 // If this is the entry block, emit arguments.
3460 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003461 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00003462 SDOperand OldRoot = SDL.DAG.getRoot();
3463 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00003464
Chris Lattner6871b232005-10-30 19:42:35 +00003465 unsigned a = 0;
3466 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3467 AI != E; ++AI, ++a)
3468 if (!AI->use_empty()) {
3469 SDL.setValue(AI, Args[a]);
Evan Cheng3784f3c52006-04-27 08:29:42 +00003470
Chris Lattner6871b232005-10-30 19:42:35 +00003471 // If this argument is live outside of the entry block, insert a copy from
3472 // whereever we got it to the vreg that other BB's will reference it as.
3473 if (FuncInfo.ValueMap.count(AI)) {
3474 SDOperand Copy =
3475 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
3476 UnorderedChains.push_back(Copy);
3477 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00003478 }
Chris Lattner6871b232005-10-30 19:42:35 +00003479
Chris Lattner6871b232005-10-30 19:42:35 +00003480 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner957cb672006-05-16 06:10:58 +00003481 // FIXME: this should insert code into the DAG!
Chris Lattner6871b232005-10-30 19:42:35 +00003482 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00003483}
3484
Chris Lattner7a60d912005-01-07 07:47:53 +00003485void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3486 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemaned728c12006-03-27 01:32:24 +00003487 FunctionLoweringInfo &FuncInfo) {
Chris Lattner7a60d912005-01-07 07:47:53 +00003488 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00003489
3490 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00003491
Chris Lattner6871b232005-10-30 19:42:35 +00003492 // Lower any arguments needed in this block if this is the entry block.
3493 if (LLVMBB == &LLVMBB->getParent()->front())
3494 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00003495
3496 BB = FuncInfo.MBBMap[LLVMBB];
3497 SDL.setCurrentBasicBlock(BB);
3498
3499 // Lower all of the non-terminator instructions.
3500 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3501 I != E; ++I)
3502 SDL.visit(*I);
Nate Begemaned728c12006-03-27 01:32:24 +00003503
Chris Lattner7a60d912005-01-07 07:47:53 +00003504 // Ensure that all instructions which are used outside of their defining
3505 // blocks are available as virtual registers.
3506 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00003507 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00003508 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00003509 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00003510 UnorderedChains.push_back(
3511 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00003512 }
3513
3514 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
3515 // ensure constants are generated when needed. Remember the virtual registers
3516 // that need to be added to the Machine PHI nodes as input. We cannot just
3517 // directly add them, because expansion might result in multiple MBB's for one
3518 // BB. As such, the start of the BB might correspond to a different MBB than
3519 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00003520 //
Chris Lattner7a60d912005-01-07 07:47:53 +00003521
3522 // Emit constants only once even if used by multiple PHI nodes.
3523 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattner707339a52006-09-07 01:59:34 +00003524
Chris Lattner7a60d912005-01-07 07:47:53 +00003525 // Check successor nodes PHI nodes that expect a constant to be available from
3526 // this block.
3527 TerminatorInst *TI = LLVMBB->getTerminator();
3528 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3529 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattner707339a52006-09-07 01:59:34 +00003530 if (!isa<PHINode>(SuccBB->begin())) continue;
3531
Chris Lattner7a60d912005-01-07 07:47:53 +00003532 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
3533 PHINode *PN;
3534
3535 // At this point we know that there is a 1-1 correspondence between LLVM PHI
3536 // nodes and Machine PHI nodes, but the incoming operands have not been
3537 // emitted yet.
3538 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00003539 (PN = dyn_cast<PHINode>(I)); ++I)
3540 if (!PN->use_empty()) {
3541 unsigned Reg;
3542 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3543 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3544 unsigned &RegOut = ConstantsOut[C];
3545 if (RegOut == 0) {
3546 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00003547 UnorderedChains.push_back(
3548 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00003549 }
3550 Reg = RegOut;
3551 } else {
3552 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00003553 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00003554 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00003555 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3556 "Didn't codegen value into a register!??");
3557 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00003558 UnorderedChains.push_back(
3559 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00003560 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003561 }
Misha Brukman835702a2005-04-21 22:36:52 +00003562
Chris Lattner8ea875f2005-01-07 21:34:19 +00003563 // Remember that this register needs to added to the machine PHI node as
3564 // the input for this MBB.
Chris Lattnerba380352006-03-31 02:12:18 +00003565 MVT::ValueType VT = TLI.getValueType(PN->getType());
3566 unsigned NumElements;
3567 if (VT != MVT::Vector)
3568 NumElements = TLI.getNumElements(VT);
3569 else {
3570 MVT::ValueType VT1,VT2;
3571 NumElements =
3572 TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3573 VT1, VT2);
3574 }
Chris Lattner8ea875f2005-01-07 21:34:19 +00003575 for (unsigned i = 0, e = NumElements; i != e; ++i)
3576 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00003577 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003578 }
3579 ConstantsOut.clear();
3580
Chris Lattner718b5c22005-01-13 17:59:43 +00003581 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00003582 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00003583 SDOperand Root = SDL.getRoot();
3584 if (Root.getOpcode() != ISD::EntryToken) {
3585 unsigned i = 0, e = UnorderedChains.size();
3586 for (; i != e; ++i) {
3587 assert(UnorderedChains[i].Val->getNumOperands() > 1);
3588 if (UnorderedChains[i].Val->getOperand(0) == Root)
3589 break; // Don't add the root if we already indirectly depend on it.
3590 }
3591
3592 if (i == e)
3593 UnorderedChains.push_back(Root);
3594 }
Chris Lattnerc24a1d32006-08-08 02:23:42 +00003595 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3596 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattner718b5c22005-01-13 17:59:43 +00003597 }
3598
Chris Lattner7a60d912005-01-07 07:47:53 +00003599 // Lower the terminator after the copies are emitted.
3600 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00003601
Nate Begemaned728c12006-03-27 01:32:24 +00003602 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003603 // lowering, as well as any jump table information.
Nate Begemaned728c12006-03-27 01:32:24 +00003604 SwitchCases.clear();
3605 SwitchCases = SDL.SwitchCases;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003606 JT = SDL.JT;
Nate Begemaned728c12006-03-27 01:32:24 +00003607
Chris Lattner4108bb02005-01-17 19:43:36 +00003608 // Make sure the root of the DAG is up-to-date.
3609 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00003610}
3611
Nate Begemaned728c12006-03-27 01:32:24 +00003612void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeydcb2b832006-10-16 20:52:31 +00003613 // Get alias analysis for load/store combining.
3614 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3615
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003616 // Run the DAG combiner in pre-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003617 DAG.Combine(false, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003618
Chris Lattner7a60d912005-01-07 07:47:53 +00003619 DEBUG(std::cerr << "Lowered selection DAG:\n");
3620 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003621
Chris Lattner7a60d912005-01-07 07:47:53 +00003622 // Second step, hack on the DAG until it only uses operations and types that
3623 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00003624 DAG.Legalize();
Nate Begemaned728c12006-03-27 01:32:24 +00003625
Chris Lattner7a60d912005-01-07 07:47:53 +00003626 DEBUG(std::cerr << "Legalized selection DAG:\n");
3627 DEBUG(DAG.dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003628
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00003629 // Run the DAG combiner in post-legalize mode.
Jim Laskeydcb2b832006-10-16 20:52:31 +00003630 DAG.Combine(true, AA);
Nate Begeman007c6502005-09-07 00:15:36 +00003631
Evan Cheng739a6a42006-01-21 02:32:06 +00003632 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng51ab4492006-04-28 02:09:19 +00003633
Chris Lattner5ca31d92005-03-30 01:10:47 +00003634 // Third, instruction select all of the operations to machine code, adding the
3635 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00003636 InstructionSelectBasicBlock(DAG);
Nate Begemaned728c12006-03-27 01:32:24 +00003637
Chris Lattner7a60d912005-01-07 07:47:53 +00003638 DEBUG(std::cerr << "Selected machine code:\n");
3639 DEBUG(BB->dump());
Nate Begemaned728c12006-03-27 01:32:24 +00003640}
Chris Lattner7a60d912005-01-07 07:47:53 +00003641
Nate Begemaned728c12006-03-27 01:32:24 +00003642void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3643 FunctionLoweringInfo &FuncInfo) {
3644 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3645 {
3646 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3647 CurDAG = &DAG;
3648
3649 // First step, lower LLVM code to some DAG. This DAG may use operations and
3650 // types that are not supported by the target.
3651 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3652
3653 // Second step, emit the lowered DAG as machine code.
3654 CodeGenAndEmitDAG(DAG);
3655 }
3656
Chris Lattner5ca31d92005-03-30 01:10:47 +00003657 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00003658 // PHI nodes in successors.
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003659 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemaned728c12006-03-27 01:32:24 +00003660 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3661 MachineInstr *PHI = PHINodesToUpdate[i].first;
3662 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3663 "This is not a machine PHI node that we are updating!");
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003664 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemaned728c12006-03-27 01:32:24 +00003665 PHI->addMachineBasicBlockOperand(BB);
3666 }
3667 return;
Chris Lattner7a60d912005-01-07 07:47:53 +00003668 }
Nate Begemaned728c12006-03-27 01:32:24 +00003669
Nate Begeman866b4b42006-04-23 06:26:20 +00003670 // If the JumpTable record is filled in, then we need to emit a jump table.
3671 // Updating the PHI nodes is tricky in this case, since we need to determine
3672 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003673 if (JT.Reg) {
3674 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3675 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3676 CurDAG = &SDAG;
3677 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman866b4b42006-04-23 06:26:20 +00003678 MachineBasicBlock *RangeBB = BB;
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003679 // Set the current basic block to the mbb we wish to insert the code into
3680 BB = JT.MBB;
3681 SDL.setCurrentBasicBlock(BB);
3682 // Emit the code
3683 SDL.visitJumpTable(JT);
3684 SDAG.setRoot(SDL.getRoot());
3685 CodeGenAndEmitDAG(SDAG);
3686 // Update PHI Nodes
3687 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3688 MachineInstr *PHI = PHINodesToUpdate[pi].first;
3689 MachineBasicBlock *PHIBB = PHI->getParent();
3690 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3691 "This is not a machine PHI node that we are updating!");
Nate Begemandf488392006-05-03 03:48:02 +00003692 if (PHIBB == JT.Default) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003693 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00003694 PHI->addMachineBasicBlockOperand(RangeBB);
3695 }
3696 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattneraf23f9b2006-09-05 02:31:13 +00003697 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemandf488392006-05-03 03:48:02 +00003698 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman4ca2ea52006-04-22 18:53:45 +00003699 }
3700 }
3701 return;
3702 }
3703
Chris Lattner76a7bc82006-10-22 23:00:53 +00003704 // If the switch block involved a branch to one of the actual successors, we
3705 // need to update PHI nodes in that block.
3706 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3707 MachineInstr *PHI = PHINodesToUpdate[i].first;
3708 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3709 "This is not a machine PHI node that we are updating!");
3710 if (BB->isSuccessor(PHI->getParent())) {
3711 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
3712 PHI->addMachineBasicBlockOperand(BB);
3713 }
3714 }
3715
Nate Begemaned728c12006-03-27 01:32:24 +00003716 // If we generated any switch lowering information, build and codegen any
3717 // additional DAGs necessary.
Chris Lattner707339a52006-09-07 01:59:34 +00003718 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Nate Begemaned728c12006-03-27 01:32:24 +00003719 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3720 CurDAG = &SDAG;
3721 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattner707339a52006-09-07 01:59:34 +00003722
Nate Begemaned728c12006-03-27 01:32:24 +00003723 // Set the current basic block to the mbb we wish to insert the code into
3724 BB = SwitchCases[i].ThisBB;
3725 SDL.setCurrentBasicBlock(BB);
Chris Lattner707339a52006-09-07 01:59:34 +00003726
Nate Begemaned728c12006-03-27 01:32:24 +00003727 // Emit the code
3728 SDL.visitSwitchCase(SwitchCases[i]);
3729 SDAG.setRoot(SDL.getRoot());
3730 CodeGenAndEmitDAG(SDAG);
Chris Lattner707339a52006-09-07 01:59:34 +00003731
3732 // Handle any PHI nodes in successors of this chunk, as if we were coming
3733 // from the original BB before switch expansion. Note that PHI nodes can
3734 // occur multiple times in PHINodesToUpdate. We have to be very careful to
3735 // handle them the right number of times.
3736 while ((BB = SwitchCases[i].LHSBB)) { // Handle LHS and RHS.
3737 for (MachineBasicBlock::iterator Phi = BB->begin();
3738 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
3739 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
3740 for (unsigned pn = 0; ; ++pn) {
3741 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
3742 if (PHINodesToUpdate[pn].first == Phi) {
3743 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
3744 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
3745 break;
3746 }
3747 }
Nate Begemaned728c12006-03-27 01:32:24 +00003748 }
Chris Lattner707339a52006-09-07 01:59:34 +00003749
3750 // Don't process RHS if same block as LHS.
3751 if (BB == SwitchCases[i].RHSBB)
3752 SwitchCases[i].RHSBB = 0;
3753
3754 // If we haven't handled the RHS, do so now. Otherwise, we're done.
3755 SwitchCases[i].LHSBB = SwitchCases[i].RHSBB;
3756 SwitchCases[i].RHSBB = 0;
Nate Begemaned728c12006-03-27 01:32:24 +00003757 }
Chris Lattner707339a52006-09-07 01:59:34 +00003758 assert(SwitchCases[i].LHSBB == 0 && SwitchCases[i].RHSBB == 0);
Chris Lattner5ca31d92005-03-30 01:10:47 +00003759 }
Chris Lattner7a60d912005-01-07 07:47:53 +00003760}
Evan Cheng739a6a42006-01-21 02:32:06 +00003761
Jim Laskey95eda5b2006-08-01 14:21:23 +00003762
Evan Cheng739a6a42006-01-21 02:32:06 +00003763//===----------------------------------------------------------------------===//
3764/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3765/// target node in the graph.
3766void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3767 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00003768
Jim Laskey29e635d2006-08-02 12:30:23 +00003769 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey95eda5b2006-08-01 14:21:23 +00003770
3771 if (!Ctor) {
Jim Laskey29e635d2006-08-02 12:30:23 +00003772 Ctor = ISHeuristic;
Jim Laskey17c67ef2006-08-01 19:14:14 +00003773 RegisterScheduler::setDefault(Ctor);
Evan Chengc1e1d972006-01-23 07:01:07 +00003774 }
Jim Laskey95eda5b2006-08-01 14:21:23 +00003775
Jim Laskey03593f72006-08-01 18:29:48 +00003776 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnere23928c2006-01-21 19:12:11 +00003777 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00003778 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00003779}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003780
Chris Lattner47639db2006-03-06 00:22:00 +00003781
Jim Laskey03593f72006-08-01 18:29:48 +00003782HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3783 return new HazardRecognizer();
3784}
3785
Chris Lattner6df34962006-10-11 03:58:02 +00003786//===----------------------------------------------------------------------===//
3787// Helper functions used by the generated instruction selector.
3788//===----------------------------------------------------------------------===//
3789// Calls to these methods are generated by tblgen.
3790
3791/// CheckAndMask - The isel is trying to match something like (and X, 255). If
3792/// the dag combiner simplified the 255, we still want to match. RHS is the
3793/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
3794/// specified in the .td file (e.g. 255).
3795bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
3796 int64_t DesiredMaskS) {
3797 uint64_t ActualMask = RHS->getValue();
3798 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
3799
3800 // If the actual mask exactly matches, success!
3801 if (ActualMask == DesiredMask)
3802 return true;
3803
3804 // If the actual AND mask is allowing unallowed bits, this doesn't match.
3805 if (ActualMask & ~DesiredMask)
3806 return false;
3807
3808 // Otherwise, the DAG Combiner may have proven that the value coming in is
3809 // either already zero or is not demanded. Check for known zero input bits.
3810 uint64_t NeededMask = DesiredMask & ~ActualMask;
3811 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
3812 return true;
3813
3814 // TODO: check to see if missing bits are just not demanded.
3815
3816 // Otherwise, this pattern doesn't match.
3817 return false;
3818}
3819
3820/// CheckOrMask - The isel is trying to match something like (or X, 255). If
3821/// the dag combiner simplified the 255, we still want to match. RHS is the
3822/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
3823/// specified in the .td file (e.g. 255).
3824bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
3825 int64_t DesiredMaskS) {
3826 uint64_t ActualMask = RHS->getValue();
3827 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
3828
3829 // If the actual mask exactly matches, success!
3830 if (ActualMask == DesiredMask)
3831 return true;
3832
3833 // If the actual AND mask is allowing unallowed bits, this doesn't match.
3834 if (ActualMask & ~DesiredMask)
3835 return false;
3836
3837 // Otherwise, the DAG Combiner may have proven that the value coming in is
3838 // either already zero or is not demanded. Check for known zero input bits.
3839 uint64_t NeededMask = DesiredMask & ~ActualMask;
3840
3841 uint64_t KnownZero, KnownOne;
3842 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
3843
3844 // If all the missing bits in the or are already known to be set, match!
3845 if ((NeededMask & KnownOne) == NeededMask)
3846 return true;
3847
3848 // TODO: check to see if missing bits are just not demanded.
3849
3850 // Otherwise, this pattern doesn't match.
3851 return false;
3852}
3853
Jim Laskey03593f72006-08-01 18:29:48 +00003854
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003855/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
3856/// by tblgen. Others should not call it.
3857void SelectionDAGISel::
3858SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
3859 std::vector<SDOperand> InOps;
3860 std::swap(InOps, Ops);
3861
3862 Ops.push_back(InOps[0]); // input chain.
3863 Ops.push_back(InOps[1]); // input asm string.
3864
Chris Lattnerdcf785b2006-02-24 02:13:54 +00003865 unsigned i = 2, e = InOps.size();
3866 if (InOps[e-1].getValueType() == MVT::Flag)
3867 --e; // Don't process a flag operand if it is here.
3868
3869 while (i != e) {
3870 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
3871 if ((Flags & 7) != 4 /*MEM*/) {
3872 // Just skip over this operand, copying the operands verbatim.
3873 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
3874 i += (Flags >> 3) + 1;
3875 } else {
3876 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
3877 // Otherwise, this is a memory operand. Ask the target to select it.
3878 std::vector<SDOperand> SelOps;
3879 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
3880 std::cerr << "Could not match memory address. Inline asm failure!\n";
3881 exit(1);
3882 }
3883
3884 // Add this to the output node.
3885 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3886 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3887 i += 2;
3888 }
3889 }
3890
3891 // Add the flag input back if present.
3892 if (e != InOps.size())
3893 Ops.push_back(InOps.back());
3894}