1 //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code to emit Aggregate Expr nodes as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CodeGenModule.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/StmtVisitor.h" 18 #include "llvm/Constants.h" 19 #include "llvm/Function.h" 20 #include "llvm/GlobalVariable.h" 21 #include "llvm/Support/Compiler.h" 22 #include "llvm/Intrinsics.h" 23 using namespace clang; 24 using namespace CodeGen; 25 26 //===----------------------------------------------------------------------===// 27 // Aggregate Expression Emitter 28 //===----------------------------------------------------------------------===// 29 30 namespace { 31 class VISIBILITY_HIDDEN AggExprEmitter : public StmtVisitor<AggExprEmitter> { 32 CodeGenFunction &CGF; 33 llvm::IRBuilder<> &Builder; 34 llvm::Value *DestPtr; 35 bool VolatileDest; 36 public: 37 AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool volatileDest) 38 : CGF(cgf), Builder(CGF.Builder), 39 DestPtr(destPtr), VolatileDest(volatileDest) { 40 } 41 42 //===--------------------------------------------------------------------===// 43 // Utilities 44 //===--------------------------------------------------------------------===// 45 46 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 47 /// represents a value lvalue, this method emits the address of the lvalue, 48 /// then loads the result into DestPtr. 49 void EmitAggLoadOfLValue(const Expr *E); 50 51 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 52 QualType EltTy); 53 54 void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty); 55 56 void EmitNonConstInit(InitListExpr *E); 57 58 //===--------------------------------------------------------------------===// 59 // Visitor Methods 60 //===--------------------------------------------------------------------===// 61 62 void VisitStmt(Stmt *S) { 63 CGF.ErrorUnsupported(S, "aggregate expression"); 64 } 65 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 66 67 // l-values. 68 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); } 69 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); } 70 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } 71 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } 72 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) 73 { EmitAggLoadOfLValue(E); } 74 75 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 76 EmitAggLoadOfLValue(E); 77 } 78 79 // Operators. 80 // case Expr::UnaryOperatorClass: 81 // case Expr::CastExprClass: 82 void VisitImplicitCastExpr(ImplicitCastExpr *E); 83 void VisitCallExpr(const CallExpr *E); 84 void VisitStmtExpr(const StmtExpr *E); 85 void VisitBinaryOperator(const BinaryOperator *BO); 86 void VisitBinAssign(const BinaryOperator *E); 87 void VisitOverloadExpr(const OverloadExpr *E); 88 void VisitBinComma(const BinaryOperator *E); 89 90 void VisitObjCMessageExpr(ObjCMessageExpr *E); 91 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 92 EmitAggLoadOfLValue(E); 93 } 94 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E); 95 96 void VisitConditionalOperator(const ConditionalOperator *CO); 97 void VisitInitListExpr(InitListExpr *E); 98 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 99 Visit(DAE->getExpr()); 100 } 101 void VisitVAArgExpr(VAArgExpr *E); 102 103 void EmitInitializationToLValue(Expr *E, LValue Address); 104 void EmitNullInitializationToLValue(LValue Address, QualType T); 105 // case Expr::ChooseExprClass: 106 107 }; 108 } // end anonymous namespace. 109 110 //===----------------------------------------------------------------------===// 111 // Utilities 112 //===----------------------------------------------------------------------===// 113 114 void AggExprEmitter::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) { 115 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 116 117 // Aggregate assignment turns into llvm.memset. 118 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 119 if (DestPtr->getType() != BP) 120 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 121 122 // Get size and alignment info for this aggregate. 123 std::pair<uint64_t, unsigned> TypeInfo = CGF.getContext().getTypeInfo(Ty); 124 125 // FIXME: Handle variable sized types. 126 const llvm::Type *IntPtr = llvm::IntegerType::get(CGF.LLVMPointerWidth); 127 128 Builder.CreateCall4(CGF.CGM.getMemSetFn(), 129 DestPtr, 130 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty), 131 // TypeInfo.first describes size in bits. 132 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 133 llvm::ConstantInt::get(llvm::Type::Int32Ty, 134 TypeInfo.second/8)); 135 } 136 137 void AggExprEmitter::EmitAggregateCopy(llvm::Value *DestPtr, 138 llvm::Value *SrcPtr, QualType Ty) { 139 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 140 141 // Aggregate assignment turns into llvm.memmove. 142 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 143 if (DestPtr->getType() != BP) 144 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 145 if (SrcPtr->getType() != BP) 146 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp"); 147 148 // Get size and alignment info for this aggregate. 149 std::pair<uint64_t, unsigned> TypeInfo = CGF.getContext().getTypeInfo(Ty); 150 151 // FIXME: Handle variable sized types. 152 const llvm::Type *IntPtr = llvm::IntegerType::get(CGF.LLVMPointerWidth); 153 154 Builder.CreateCall4(CGF.CGM.getMemMoveFn(), 155 DestPtr, SrcPtr, 156 // TypeInfo.first describes size in bits. 157 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 158 llvm::ConstantInt::get(llvm::Type::Int32Ty, 159 TypeInfo.second/8)); 160 } 161 162 163 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 164 /// represents a value lvalue, this method emits the address of the lvalue, 165 /// then loads the result into DestPtr. 166 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) { 167 LValue LV = CGF.EmitLValue(E); 168 assert(LV.isSimple() && "Can't have aggregate bitfield, vector, etc"); 169 llvm::Value *SrcPtr = LV.getAddress(); 170 171 // If the result is ignored, don't copy from the value. 172 if (DestPtr == 0) 173 // FIXME: If the source is volatile, we must read from it. 174 return; 175 176 EmitAggregateCopy(DestPtr, SrcPtr, E->getType()); 177 } 178 179 //===----------------------------------------------------------------------===// 180 // Visitor Methods 181 //===----------------------------------------------------------------------===// 182 183 void AggExprEmitter::VisitImplicitCastExpr(ImplicitCastExpr *E) { 184 assert(CGF.getContext().typesAreCompatible( 185 E->getSubExpr()->getType().getUnqualifiedType(), 186 E->getType().getUnqualifiedType()) && 187 "Implicit cast types must be compatible"); 188 Visit(E->getSubExpr()); 189 } 190 191 void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 192 RValue RV = CGF.EmitCallExpr(E); 193 assert(RV.isAggregate() && "Return value must be aggregate value!"); 194 195 // If the result is ignored, don't copy from the value. 196 if (DestPtr == 0) 197 // FIXME: If the source is volatile, we must read from it. 198 return; 199 200 EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 201 } 202 203 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 204 RValue RV = CGF.EmitObjCMessageExpr(E); 205 assert(RV.isAggregate() && "Return value must be aggregate value!"); 206 207 // If the result is ignored, don't copy from the value. 208 if (DestPtr == 0) 209 // FIXME: If the source is volatile, we must read from it. 210 return; 211 212 EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 213 } 214 215 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 216 RValue RV = CGF.EmitObjCPropertyGet(E); 217 assert(RV.isAggregate() && "Return value must be aggregate value!"); 218 219 // If the result is ignored, don't copy from the value. 220 if (DestPtr == 0) 221 // FIXME: If the source is volatile, we must read from it. 222 return; 223 224 EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 225 } 226 227 void AggExprEmitter::VisitOverloadExpr(const OverloadExpr *E) { 228 RValue RV = CGF.EmitCallExpr(E->getFn(), E->arg_begin(), 229 E->arg_end(CGF.getContext())); 230 231 assert(RV.isAggregate() && "Return value must be aggregate value!"); 232 233 // If the result is ignored, don't copy from the value. 234 if (DestPtr == 0) 235 // FIXME: If the source is volatile, we must read from it. 236 return; 237 238 EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 239 } 240 241 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 242 CGF.EmitAnyExpr(E->getLHS()); 243 CGF.EmitAggExpr(E->getRHS(), DestPtr, false); 244 } 245 246 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 247 CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest); 248 } 249 250 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 251 CGF.ErrorUnsupported(E, "aggregate binary expression"); 252 } 253 254 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 255 // For an assignment to work, the value on the right has 256 // to be compatible with the value on the left. 257 assert(CGF.getContext().typesAreCompatible( 258 E->getLHS()->getType().getUnqualifiedType(), 259 E->getRHS()->getType().getUnqualifiedType()) 260 && "Invalid assignment"); 261 LValue LHS = CGF.EmitLValue(E->getLHS()); 262 263 // We have to special case property setters, otherwise we must have 264 // a simple lvalue (no aggregates inside vectors, bitfields). 265 if (LHS.isPropertyRef()) { 266 // FIXME: Volatility? 267 llvm::Value *AggLoc = DestPtr; 268 if (!AggLoc) 269 AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType())); 270 CGF.EmitAggExpr(E->getRHS(), AggLoc, false); 271 CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(), 272 RValue::getAggregate(AggLoc)); 273 } else { 274 // Codegen the RHS so that it stores directly into the LHS. 275 CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), false /*FIXME: VOLATILE LHS*/); 276 277 if (DestPtr == 0) 278 return; 279 280 // If the result of the assignment is used, copy the RHS there also. 281 EmitAggregateCopy(DestPtr, LHS.getAddress(), E->getType()); 282 } 283 } 284 285 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) { 286 llvm::BasicBlock *LHSBlock = llvm::BasicBlock::Create("cond.?"); 287 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("cond.:"); 288 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("cond.cont"); 289 290 llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond()); 291 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock); 292 293 CGF.EmitBlock(LHSBlock); 294 295 // Handle the GNU extension for missing LHS. 296 assert(E->getLHS() && "Must have LHS for aggregate value"); 297 298 Visit(E->getLHS()); 299 Builder.CreateBr(ContBlock); 300 LHSBlock = Builder.GetInsertBlock(); 301 302 CGF.EmitBlock(RHSBlock); 303 304 Visit(E->getRHS()); 305 Builder.CreateBr(ContBlock); 306 RHSBlock = Builder.GetInsertBlock(); 307 308 CGF.EmitBlock(ContBlock); 309 } 310 311 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 312 llvm::Value *ArgValue = CGF.EmitLValue(VE->getSubExpr()).getAddress(); 313 llvm::Value *V = Builder.CreateVAArg(ArgValue, CGF.ConvertType(VE->getType())); 314 if (DestPtr) 315 // FIXME: volatility 316 Builder.CreateStore(V, DestPtr); 317 } 318 319 void AggExprEmitter::EmitNonConstInit(InitListExpr *E) { 320 321 const llvm::PointerType *APType = 322 cast<llvm::PointerType>(DestPtr->getType()); 323 const llvm::Type *DestType = APType->getElementType(); 324 325 if (const llvm::ArrayType *AType = dyn_cast<llvm::ArrayType>(DestType)) { 326 unsigned NumInitElements = E->getNumInits(); 327 328 unsigned i; 329 for (i = 0; i != NumInitElements; ++i) { 330 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 331 Expr *Init = E->getInit(i); 332 if (isa<InitListExpr>(Init)) 333 CGF.EmitAggExpr(Init, NextVal, VolatileDest); 334 else 335 // FIXME: volatility 336 Builder.CreateStore(CGF.EmitScalarExpr(Init), NextVal); 337 } 338 339 // Emit remaining default initializers 340 unsigned NumArrayElements = AType->getNumElements(); 341 QualType QType = E->getInit(0)->getType(); 342 const llvm::Type *EType = AType->getElementType(); 343 for (/*Do not initialize i*/; i < NumArrayElements; ++i) { 344 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 345 if (EType->isSingleValueType()) 346 // FIXME: volatility 347 Builder.CreateStore(llvm::Constant::getNullValue(EType), NextVal); 348 else 349 EmitAggregateClear(NextVal, QType); 350 } 351 } else 352 assert(false && "Invalid initializer"); 353 } 354 355 void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) { 356 // FIXME: Are initializers affected by volatile? 357 if (E->getType()->isComplexType()) { 358 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false); 359 } else if (CGF.hasAggregateLLVMType(E->getType())) { 360 CGF.EmitAnyExpr(E, LV.getAddress(), false); 361 } else { 362 CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, E->getType()); 363 } 364 } 365 366 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { 367 if (!CGF.hasAggregateLLVMType(T)) { 368 // For non-aggregates, we can store zero 369 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T)); 370 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T); 371 } else { 372 // Otherwise, just memset the whole thing to zero. This is legal 373 // because in LLVM, all default initializers are guaranteed to have a 374 // bit pattern of all zeros. 375 // There's a potential optimization opportunity in combining 376 // memsets; that would be easy for arrays, but relatively 377 // difficult for structures with the current code. 378 llvm::Value *MemSet = CGF.CGM.getIntrinsic(llvm::Intrinsic::memset_i64); 379 uint64_t Size = CGF.getContext().getTypeSize(T); 380 381 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 382 llvm::Value* DestPtr = Builder.CreateBitCast(LV.getAddress(), BP, "tmp"); 383 Builder.CreateCall4(MemSet, DestPtr, 384 llvm::ConstantInt::get(llvm::Type::Int8Ty, 0), 385 llvm::ConstantInt::get(llvm::Type::Int64Ty, Size/8), 386 llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); 387 } 388 } 389 390 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 391 // FIXME: For constant expressions, call into const expr emitter so 392 // that we can emit a memcpy instead of storing the individual 393 // members. This is purely for perf; both codepaths lead to 394 // equivalent (although not necessarily identical) code. It's worth 395 // noting that LLVM keeps on getting smarter, though, so it might 396 // not be worth bothering. 397 398 // Handle initialization of an array. 399 if (E->getType()->isArrayType()) { 400 const llvm::PointerType *APType = 401 cast<llvm::PointerType>(DestPtr->getType()); 402 const llvm::ArrayType *AType = 403 cast<llvm::ArrayType>(APType->getElementType()); 404 405 uint64_t NumInitElements = E->getNumInits(); 406 407 if (E->getNumInits() > 0) { 408 QualType T1 = E->getType(); 409 QualType T2 = E->getInit(0)->getType(); 410 if (CGF.getContext().getCanonicalType(T1).getUnqualifiedType() == 411 CGF.getContext().getCanonicalType(T2).getUnqualifiedType()) { 412 EmitAggLoadOfLValue(E->getInit(0)); 413 return; 414 } 415 } 416 417 uint64_t NumArrayElements = AType->getNumElements(); 418 QualType ElementType = CGF.getContext().getCanonicalType(E->getType()); 419 ElementType =CGF.getContext().getAsArrayType(ElementType)->getElementType(); 420 421 unsigned CVRqualifier = ElementType.getCVRQualifiers(); 422 423 for (uint64_t i = 0; i != NumArrayElements; ++i) { 424 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 425 if (i < NumInitElements) 426 EmitInitializationToLValue(E->getInit(i), 427 LValue::MakeAddr(NextVal, CVRqualifier)); 428 else 429 EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, CVRqualifier), 430 ElementType); 431 } 432 return; 433 } 434 435 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 436 437 // Do struct initialization; this code just sets each individual member 438 // to the approprate value. This makes bitfield support automatic; 439 // the disadvantage is that the generated code is more difficult for 440 // the optimizer, especially with bitfields. 441 unsigned NumInitElements = E->getNumInits(); 442 RecordDecl *SD = E->getType()->getAsRecordType()->getDecl(); 443 unsigned NumMembers = SD->getNumMembers() - SD->hasFlexibleArrayMember(); 444 unsigned CurInitVal = 0; 445 bool isUnion = E->getType()->isUnionType(); 446 447 // Here we iterate over the fields; this makes it simpler to both 448 // default-initialize fields and skip over unnamed fields. 449 for (unsigned CurFieldNo = 0; CurFieldNo != NumMembers; ++CurFieldNo) { 450 FieldDecl *CurField = SD->getMember(CurFieldNo); 451 if (CurField->getIdentifier() == 0) { 452 // Initializers can't initialize unnamed fields, e.g. "int : 20;" 453 continue; 454 } 455 // FIXME: volatility 456 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, CurField, isUnion,0); 457 if (CurInitVal < NumInitElements) { 458 // Store the initializer into the field 459 // This will probably have to get a bit smarter when we support 460 // designators in initializers 461 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc); 462 } else { 463 // We're out of initalizers; default-initialize to null 464 EmitNullInitializationToLValue(FieldLoc, CurField->getType()); 465 } 466 467 // Unions only initialize one field. 468 // (things can get weird with designators, but they aren't 469 // supported yet.) 470 if (E->getType()->isUnionType()) 471 break; 472 } 473 } 474 475 //===----------------------------------------------------------------------===// 476 // Entry Points into this File 477 //===----------------------------------------------------------------------===// 478 479 /// EmitAggExpr - Emit the computation of the specified expression of 480 /// aggregate type. The result is computed into DestPtr. Note that if 481 /// DestPtr is null, the value of the aggregate expression is not needed. 482 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr, 483 bool VolatileDest) { 484 assert(E && hasAggregateLLVMType(E->getType()) && 485 "Invalid aggregate expression to emit"); 486 487 AggExprEmitter(*this, DestPtr, VolatileDest).Visit(const_cast<Expr*>(E)); 488 } 489